问题
I learned that it's recommended to use BigDecimal
instead of Float
, but this one is either a bug or highlights the esoteric nature of Float
. It seems that Float#round(2)
has a problem with "1.015", "1.025" and "1.035".
1.015.round(2)
=> 1.01 # => WRONG .. should be 1.02
1.025.round(2)
=> 1.02 # => WRONG .. should be 1.03
1.035.round(2)
=> 1.03 # => WRONG .. should be 1.04
1.045.round(2)
=> 1.05 # => CORRECT
1.016.round(2)
=> 1.02 # => CORRECT
round(3)
works fine.
1.0015.round(3)
=> 1.002 # => CORRECT
1.235.round(2)
=> 1.24 # => CORRECT
To monkey patch this in a Rails app, I did this:
config/initializers/float_mp.rb
require 'bigdecimal'
class Float
def round(val=0)
BigDecimal.new(self.to_s).round(val).to_f
end
end
This seems to be a weird and expensive work-around. Could this be a bug in Float#round
?
回答1:
AFAICS the ruby round() works correctly. Presumably it's just a wrapper around the round() function in libm anyway.
So the reason is that your floating point literals cannot be represented exactly in binary. E.g. "1.015" printed with a few more decimals gives "1.0149999999999999"; thus when rounding to two decimal digits, 1.01 is closer to the true value than 1.02. And so on for your other examples as well.
Also keep in mind that the default IEEE 754 rounding mode is "Round to nearest, ties to even" which is not the same as "Round to nearest, ties away from zero" which is what you may be familiar with from school.
来源:https://stackoverflow.com/questions/12455633/ruby-floatround-method-behaves-incorrectly-with-round2