Why does round()
do a better job than the printf
type of string formatting?
ruby-1.9.2-p0 > "%.0f" % 14.5
=> "14"
ruby-1.9.2-p0 > "%.0f" % 14.5000001
=> "15"
ruby-1.9.2-p0 > 14.5.round
=> 15
Why does round()
do a better job than the printf
type of string formatting?
ruby-1.9.2-p0 > "%.0f" % 14.5
=> "14"
ruby-1.9.2-p0 > "%.0f" % 14.5000001
=> "15"
ruby-1.9.2-p0 > 14.5.round
=> 15
Just because you've learned in school that .5
is always rounded up does not mean that's the only correct way to do it. There are quite a number of different rounding modes; what you're looking at is most likely "round to even", which rounds .5
towards the even integer; this has the advantage of not producing an overall upwards bias like always rounding up does.
High-quality math libraries like Ruby Flt generally provide a way to explicitly choose the rounding mode.
"Better job"? No, not if you care about things averaging out. Hence, round towards even.