Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent rounding of floating point #34815

Closed
jeetsang opened this issue Oct 10, 2019 · 1 comment
Closed

Inconsistent rounding of floating point #34815

jeetsang opened this issue Oct 10, 2019 · 1 comment

Comments

@jeetsang
Copy link

jeetsang commented Oct 10, 2019

What version of Go are you using (go version)?

$ go version go1.12.1 darwin/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env
$ go env
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/jitendra/Library/Caches/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/jitendra/go"
GOPROXY=""
GORACE=""
GOROOT="/usr/local/Cellar/go/1.12.1/libexec"
GOTMPDIR=""
GOTOOLDIR="/usr/local/Cellar/go/1.12.1/libexec/pkg/tool/darwin_amd64"
GCCGO="gccgo"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/x8/68sd4h_x0v140qx5jb18mp5c0000gn/T/go-build192220704=/tmp/go-build -gno-record-gcc-switches -fno-common

What did you do?

fmt.Printf("%.1f", 3.85)
fmt.Println()
fmt.Printf("%.1f", 4.85)

What did you expect to see?

3.9

4.9

What did you see instead?

3.9

4.8

@ALTree
Copy link
Member

ALTree commented Oct 10, 2019

The rounding is correct. Neither 3.85 nor 4.85 are exactly representable as IEEE-754 floats, so even if you wrote "3.85" and "4.85" in your code, what you'll really get is the nearest representable float64s, which are:

3.850000000000000088817841970012523233890533447265625
4.8499999999999996447286321199499070644378662109375

which explains why the first is rounded to .9 and the second to .8

Closing here, since this is working as intended.

@ALTree ALTree closed this as completed Oct 10, 2019
@golang golang locked and limited conversation to collaborators Oct 9, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants