1

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 
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • Eeemmm... because... because. http://en.wikipedia.org/wiki/Printf and http://en.wikipedia.org/wiki/Rounding#Rounding_to_integer - a lot of stuff to read. – Nakilon Nov 20 '10 at 04:15
  • Equivalent to [this question](http://stackoverflow.com/questions/588004/is-javascripts-math-broken) even though it's in another language. – Andrew Grimm Nov 20 '10 at 12:49
  • @Andrew Grimm It's not equivalent because it's trying to get at the difference between `"%.0f" % 14.5` and `14.5.round.to_s` (e.g. what are the specific nuance rules of %f?) –  Nov 20 '10 at 23:16

2 Answers2

3

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.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
1

"Better job"? No, not if you care about things averaging out. Hence, round towards even.

tchrist
  • 78,834
  • 30
  • 123
  • 180
  • 1
    round towards even? what do you mean? rounding only to 14 and then to 16 next? – nonopolarity Nov 20 '10 at 04:48
  • 2
    That's exactly what he means. If you always round x.5 up, you end up with a small, but statistically significant bias where a total or average is overstated. Rounding x.5 to the nearest even number counters the bias effect. – Bevan Nov 25 '10 at 00:44