From: Phrogz Date: 2010-01-02T13:45:05+09:00 Subject: Re: Rounding float in ruby via .round On Jan 1, 9:32 pm, Phrogz wrote: > On Jan 1, 7:22 pm, pharrington wrote: > > > On Jan 1, 9:13 pm, Phillip Gawlowski wrote: > > > > Which Ruby are you on? > > > <= 1.8.7 > > You could do (untested on 1.8): > > if Float.instance_method(:round).arity == 0 >   class Float >     alias_method :_orig_round, :round >     def round( decimals=0 ) >       factor = 10**decimals >       (self*factor)._orig_round / factor >     end >   end > end > > Even gives you rounding to 'negative' decimal places, as in 1.9 Note that this gives you a Float as the result, which you may need to use sprintf to display as desired. If you want something like JavaScript's toFixed(), returning a string certain to be displaying the precision you wanted, you might instead do (also untested): class Numeric def round_to_str( decimals=0 ) if decimals >= 0 "%.#{decimals}f" % self else factor = 10**-decimals ((self/factor).round * factor).to_s end end end