From: Phrogz Date: 2010-01-02T13:50:14+09:00 Subject: Re: Rounding float in ruby via .round On Jan 1, 9:32 pm, Phrogz wrote: > 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 Bah, should have tested. Of course the original round returns a fixnum, so dividing by the factor at that point really doesn't do what I had intended. Here are a few alternatives. Poke fun at them and/or benchmark as you see fit: if Float.instance_method(:round).arity == 0 class Float alias_method :_orig_round, :round def round( decimals=0 ) factor = 10.0**decimals (self*factor)._orig_round / factor end end end 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.to_f / factor end end end 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.to_f end end end