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
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
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