0

In my rails console, when I add up to floats, i get a suprising result. Why?

977.90 + 112.49
=> 1090.3899999999999

Isn't the answer 1090.39 ? Why does ruby/rails return the answer it does?

mrzasa
  • 22,895
  • 11
  • 56
  • 94
Will
  • 4,498
  • 2
  • 38
  • 65
  • OK, i googled more. Floats are inaccurate represnetations of numbers. fun! – Will Jul 26 '19 at 10:03
  • This article is helpful https://corainchicago.github.io/blog/why-does-ruby-add-numbers-wrong/ – Will Jul 26 '19 at 10:04
  • @Amadan: Or `Integer`s. If those numbers represent money, you could do all the calculation in cents. `97790 + 11249 == 109039`, and divide by `100.0` before displaying the results. `(97790 + 11249) / 100.0 #=> 1090.39`. – Eric Duminil Jul 26 '19 at 11:28

0 Answers0