Because I hate the sprintf solution, I added my own (probably much slower) hand-rolled version. (The algorithm is taken from the ECMAScript specification.)
Numeric#round_to
http://phrogz.net/RubyLibs/rdoc/classes/Numeric.html
http://phrogz.net/RubyLibs/basiclibrary.rb
···
________________________________
From: Eric Anderson [mailto:eric@bigsky.realsimplehosting.com]
Sent: Thu 10/14/2004 7:34 AM
To: ruby-talk ML
Subject: Re: Rounding to X digits
Eric Anderson wrote:
Obviously I could also enhance round to take an optional
argument but I wanted to see if there was an already existing function
in the Ruby std library that will do it for me.
To follow up my own post. If there isn't a function like what I am
looking for in the standard library, I am using the following to make it
like I want.
class Float
alias :oldround :round
def round( sd=0 )
return (self * (10 ** sd)).oldround.to_f / (10**sd)
end
end