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

JSON parse gives wrong Float64 result #10920

Closed
hanabi1224 opened this issue Jul 11, 2021 · 2 comments · Fixed by #10447
Closed

JSON parse gives wrong Float64 result #10920

hanabi1224 opened this issue Jul 11, 2021 · 2 comments · Fixed by #10447

Comments

@hanabi1224
Copy link

Repro steps
Below code show difference between from_json and to_f64. (result of to_f64 is consistent with other languages while from_json is not)

num = "43.474709000000132"
puts Float64.from_json(num)
# 43.474709000000125
puts num.to_f64
# 43.47470900000013

Crystal compiler version

Crystal 1.0.0 [dd40a24] (2021-03-22)
LLVM: 10.0.0
Default target: x86_64-unknown-linux-gnu

@HertzDevil
Copy link
Contributor

HertzDevil commented Jul 11, 2021

Should be fixed by #10447

The root issue is that Float64.from_json tries to obtain the floating-point value from 43474709000000132 / 1e15, which in turn calls 43474709000000132.to_f64 / 1e15.to_f64. The significand is inexact and rounds off to 43474709000000128.0 (it is halfway between this value and 43474709000000136.0, and the ties-to-even rule chooses this value), so the division becomes inexact. If you do the same division in other programming languages you could get the same incorrect results.

@straight-shoota
Copy link
Member

Related to #10419

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants