Submitted by transami (Tue Apr 19 23:26:21 UTC 2005)
Since #round currently takes no arguments there should be no backward compatibility issues. The only catch to consider is that #round returns an Integer without an argument, but would return a Float with one. This isn't an issue as much as it is something to note.
# 4.555.round(0) #=> 5.0 # 4.555.round(1) #=> 4.6 # 4.555.round(2) #=> 4.56 # 4.555.round(3) #=> 4.555 alias :round_off :round def round( d=0.0 ) (self * (10.0 ** d)).round_off.to_f / (10.0 ** d) end
Another is to the nth degree:
# 4.555.round(1) #=> 5.0 # 4.555.round(0.1) #=> 4.6 # 4.555.round(0.01) #=> 4.56 # 4.555.round(0) #=> 4.555 alias :round_off :round def round( n ) return self if n == 0 (self * (1.0 / n)).round_off.to_f / (1.0 / n) end
Or one could specify the rounding factor directly:
# 4.555.round(1) #=> 5.0 # 4.555.round(10) #=> 4.6 # 4.555.round(100) #=> 4.56 # 4.555.round(1000) #=> 4.555 alias :round_off :round def round( a=1.0 ) (self * a).round_off.to_f / a end
Comments  Current voting  


RCRchive copyright © David Alan Black, 20032005.
Powered by .
The science form rounded a bit more aggressively  e.g., if I have one significant digit and the value 11, my rounded value would be 10. But if we cast the #round argument in terms of significant decimal places, then this makes perfect sense.
 good idea, its useful
I think this was discussed on #rubylang at some point... I like the proposal as such, but to my nonmathematical brain the simplest form would be to signal how many significant digits there will be. If you allow my fancy, how about marking the significant digits with the method/method_missing #o...?
The other urge is to support rounding to the 'nearest something' for Fixnums/Integers, too:
esaynatkari
I'm slightly concerned that this would be (ab)used for formatting of values, which would not work reliably due to the (wellknown) floating point arithmetic "issues".
In favor of the first option. It also gives you the ability to specify negative decimal places, to round to the nearest 10, 100, etc.
Users would quickly find out that it was NOT for string formatting, and learn to use (or wrap) sprintf accordingly.