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
encoding/json: float32 may not convert correctly #34559
Comments
Actually, Same can be confirmed in https://play.golang.org/p/JroJ5RijGFx |
This is not a bug. There's no way to distinguish |
This is not a bug. Here's what happens with float64s in JavaScript:
This behavior is generalized to float32s for Go's JSON parser: print as few non-zero digits as is needed to precisely identify the right float32. Note that reading the value back as a float32 reproduces the original float32. In float32 math, 2684354600 == 2684354560. Similarly, in float64 math, 123456789123456789123 == 123456789123456800000. If you want to distinguish between 2684354600 and 2684354560, the answer is to not use a float32 at all. Use a float64 instead. (In general a float32 has so little precision that it's almost never the right answer.) I'd be happy to look at examples from other languages but almost all of them are probably operating on float64s, not float32s, either because the language doesn't have float32 at all or because the language does the C-like thing where float32s become float64s in most calls. That is, try:
That's what most C-like languages would do implicitly. |
I verified 2684354432 to 2684354688 have the same value. Excuse me. |
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
yes
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
I converted a float32 value to JSON and the value went differnt.
https://play.golang.org/p/_giUH9Yq35f
What did you expect to see?
Expected to get 2684354560, the same value as before conversion.
What did you see instead?
I got 2684354600 which is different from before conversion. Since fmt.Printf can display correctly, I think it is a issue of encoding/json. If we do roughly the same thing in C#, GSon(Java), node.js, there is no issue.
This issue was first reported here.
The text was updated successfully, but these errors were encountered: