1
30.0 * 0.009 # => 0.26999999999999996

Does anybody know why this is not 0.27?

Any recommendations on what to do about this?

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
David West
  • 2,256
  • 6
  • 32
  • 62
  • 4
    that's how floating point numbers work. "we are float of borg. accuracy is irrelevant, you will be approximated" – Marc B Dec 01 '15 at 21:38
  • 1
    please read this http://www.rails-troubles.com/2011/12/ruby-float-quirks.html?m=1 – bmalets Dec 01 '15 at 21:39
  • I read it. The author suggests using BigDecimal among other things. I'm now reading . What do you do in your code base if you've addressed this problem before? I'm looking at 'What Every Computer Scientist Should Know About Floating-Point Arithmetic' as well. There's also a good article comparing different languages http://itreallymatters.net/post/386327451/floating-point-arithmetics-in-19-programming#.Vl4WN3arRpg. – David West Dec 01 '15 at 21:47
  • It all boils down to the fact that computers can't represent ***every*** float accurately in binary. Thus, arithmetic gets weird. – Charles Dec 01 '15 at 22:00

1 Answers1

2

Since you already found materials on the why subject, I will just answer the what to do part of the question. If you absolutely don't want to approximate, you have to use rational numbers:

30 * 0.009r # => (27/100)
ndnenkov
  • 35,425
  • 9
  • 72
  • 104