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

float64 member in struct output from json.Marshal not right #34949

Closed
Tomarron opened this issue Oct 17, 2019 · 5 comments
Closed

float64 member in struct output from json.Marshal not right #34949

Tomarron opened this issue Oct 17, 2019 · 5 comments

Comments

@Tomarron
Copy link

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

$ go version : 1.12

Does this issue reproduce with the latest release?

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

go env Output
$ go env

What did you do?

type A struct {
ID int json:"id"
Amount float64 json:"amount"
}

ok case:
func main() {
var a = A{ID: 1, Amount: 7.11}
var b = A{ID: 2, Amount: 1.02}
c := A{ID: 1, Amount: 0.0000}
c.Amount = a.Amount + b.Amount
fmt.Printf("%f==%+v\n", c.Amount, c)
content, err := json.Marshal(c)
fmt.Println(string(content), err)
}
output:
8.130000=={ID:1 Amount:8.13}
{"id":1,"amount":8.13}

nok case :

func main() {
var a = A{ID: 1, Amount: 8.11}
var b = A{ID: 2, Amount: 1.02}
c := A{ID: 1, Amount: 0.0000}
c.Amount = a.Amount + b.Amount
fmt.Printf("%f==%+v\n", c.Amount, c)
content, err := json.Marshal(c)
fmt.Println(string(content), err)
}
output:
9.130000=={ID:1 Amount:9.129999999999999}
{"id":1,"amount":9.129999999999999}

What did you expect to see?

9.130000=={ID:1 Amount:9.13}
{"id":1,"amount":9.13}

What did you see instead?

9.130000=={ID:1 Amount:9.129999999999999}
{"id":1,"amount":9.129999999999999}

the boundary is 8, can any explain is this a feature or bug,if feature, why? any advice to avoid the case or solution?

@networkimprov
Copy link

Note that it is not correct to use floating point types for currency values.
https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency

@bradfitz
Copy link
Contributor

See https://floating-point-gui.de

This isn't really a Go issue.

@Tomarron
Copy link
Author

can anyone explain why 8.13 is ok,but 9.13 shows 9.129999999999999, thanks a lot!

@bradfitz
Copy link
Contributor

I sent you a link above with information about floats. This isn't a Go specific thing.

@Tomarron
Copy link
Author

thanks,I will read.

@golang golang locked and limited conversation to collaborators Oct 17, 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

4 participants