9.325 round Anomalyin Ruby?

Did this in irb

9.325.round
=> 9

9.325.round(2)
=> 9.32

10.325.round(2)
=> 10.33

9.315.round(2)
=> 9.32

9.335.round(2)
=> 9.34

Is it a bug in Ruby?

  • Karthikeyan A K

Not all decimal numbers can be exactly represented by floating point
numbers:

puts ‘%.50f’ % 9.325
=> “9.32499999999999928945726423989981412887573242187500”

So the number you are rounding is actually smaller than 9.325, and
therefore correctly rounded down.

If you want exact representation of decimal numbers, you need to use
BigDecimal:

require ‘bigdecimal’
puts BigDecimal.new(‘9.325’).round(2)
=> 0.933E1

Thanks a lot Andreas