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

Adding floats shows unwanted / wrong precision #39546

Closed
factors-prateek opened this issue Jun 12, 2020 · 1 comment
Closed

Adding floats shows unwanted / wrong precision #39546

factors-prateek opened this issue Jun 12, 2020 · 1 comment

Comments

@factors-prateek
Copy link

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

$ go version
go version go1.14.2 darwin/amd64

Does this issue reproduce with the latest release?

Not sure.

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

go env Output
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/prateek/Library/Caches/go-build"
GOENV="/Users/prateek/Library/Application Support/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/prateek/Documents/workspace/factors/backend"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
GCCGO="gccgo"
AR="ar"
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/3l/wp0dvd6901q1l1bn_z8bzm1h0000gp/T/go-build389574889=/tmp/go-build -gno-record-gcc-switches -fno-common"

What did you do?

package main

import "fmt"

func main() {
    a, b := 2.2, 2.2
    fmt.Println(a + b)

    a, b = 2.2, 2.3
    fmt.Println(a + b)

    a, b = 2.2, 4.4
    fmt.Println(a + b)

    a, b = 1.1, 2.2
    fmt.Println(a + b)
}

What did you expect to see?

4.4
4.5
6.6
3.3

What did you see instead?

4.4
4.5
6.6000000000000005
3.3000000000000003
@ALTree
Copy link
Member

ALTree commented Jun 12, 2020

Println shows 6.6000000000000005 because it's closer to the actual value of 2.2 + 4.4 in IEEE-754 float64 arithmetic. If you want to truncate the value, use Printf and %f, e.g.

a, b := 2.2, 4.4
fmt.Printf("%.2f", a + b)    // prints 6.60

Closing here, since this is working as intended.

@ALTree ALTree closed this as completed Jun 12, 2020
@golang golang locked and limited conversation to collaborators Jun 12, 2021
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