7

When I add 0.1+0.2 I am getting 0.30000000000000004 but when I add the same number in ruby 1.8.7 I am getting the correct answer 0.3. I get 0.3 by rounding but I just want to get 0.3 on ruby 1.9.2 by adding 0.1 and 0.2

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Sadiksha Gautam
  • 5,032
  • 6
  • 40
  • 71

2 Answers2

11

You need bigdecimal for this to make work.

(BigDecimal('0.1') + BigDecimal("0.2")).to_f

See below link:

http://redmine.ruby-lang.org/issues/4394

ashisrai_
  • 6,438
  • 2
  • 26
  • 42
  • 3
    `"since it is ruby's bug"` - this is not a bug - it's how floating point works - the bug report claiming this as a bug was marked as rejected. – Andrew Grimm Aug 18 '11 at 05:20
7

Your old ruby lied to you:

$ ruby -v
ruby 1.8.7 (2010-06-23 patchlevel 299) [x86_64-linux]
$ irb
irb(main):001:0> printf("%40.40f\n", 0.1 + 0.2)
0.3000000000000000444089209850062616169453
=> nil

Floating point numbers are very tricky beasts.

sarnold
  • 102,305
  • 22
  • 181
  • 238
  • 2
    That's an interesting notion: it lied to you and gave you the correct answer, it shouldn't have done that. Floating point _is_ fun! – Andrew Marshall Mar 24 '11 at 06:04
  • @Andrew Marshall, thanks for the laugh. :) – sarnold Mar 24 '11 at 06:06
  • 2
    I was using ruby-1.8.7-head, not patchlevel. – Sadiksha Gautam Mar 24 '11 at 06:13
  • 2
    @Sadiksha Gautam, you get the same answer from C :) so I doubt specific patchlevel of Ruby really matters. Really, try the `printf("%40.40f\n", 0.1 + 0.2)` on any version of Ruby, Python, C, Java, etc. you can find; any language that uses IEEE-754 floating point numbers is going to give you these sorts of results. – sarnold Mar 24 '11 at 06:17
  • 1
    And Python will do the same. `>>> 0.1 + 0.2 0.30000000000000004`. It's the joy of dealing with floating point and why financial calculations don't use floats. – the Tin Man Mar 24 '11 at 06:28
  • @sarnold => That is because you might be using some kind of formatting -- "%40.40f\n". Do "%0.2f\n" instead and you will get the right answer. – ashisrai_ Mar 24 '11 at 10:40
  • 1
    @a5his, I don't _want_ "the right answer" :) The whole point of my formatting is to help Sadiksha Gautam see that his older version of Ruby was _lying_ to him about what "the right answer" was, and rounding the results before giving him the answer. – sarnold Mar 24 '11 at 10:43
  • @sarnold => Thx. I hope it helped :sadiksha – ashisrai_ Mar 24 '11 at 10:46