Did this in irb
9.325.round
=> 99.325.round(2)
=> 9.3210.325.round(2)
=> 10.339.315.round(2)
=> 9.329.335.round(2)
=> 9.34
Is it a bug in Ruby?
- Karthikeyan A K
Did this in irb
9.325.round
=> 99.325.round(2)
=> 9.3210.325.round(2)
=> 10.339.315.round(2)
=> 9.329.335.round(2)
=> 9.34
Is it a bug in Ruby?
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs