0

I am using ruby 2.3.0p0.

I have been trying to do a simple addition using 2 float numbers in ruby

irb(main):001:0> 1.50 + 14.99
=> 16.490000000000002

The desired result should be 16.49 instead of 16.490000000000002

a = 1.5
b = 14.99
c = a + b

How could I fixed this so that I could get 16.49 for variable c

Cheers.

Kenny Chan
  • 1,232
  • 1
  • 15
  • 20
  • 1
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Roman Kiselenko Jul 16 '16 at 07:58
  • Well I guess I have solve it in a way that might not be that elegant. require 'bigdecimal'; (BigDecimal('1.5') + BigDecimal('14.99')).to_f. Cheers. – Kenny Chan Jul 16 '16 at 08:14

1 Answers1

2

Since floating point numbers are not as precise as you think they are, they often include tiny bits of noise that result from various calculations, it's your responsibility to specify what level of precision you want when displaying them:

a = 1.5
b = 14.99

c = a + b

puts '%.2f' % c

The %.2f notation here means to have two places. %.9f would be nine places.

This is how floating point numbers work. Don't expect them to be neat and tidy.

tadman
  • 208,517
  • 23
  • 234
  • 262