That's the same technique he's using for ceil and floor-- seems like the
best approach available (the only thing left to do now is test whether
multiply and divide is faster than sprintf). Except that instead of
defining round_n, ceil_n, and floor_n, I would probably just redefine
the existing Float#round, Float#ceil and Float#floor methods. Because
he's got n=0 in the method signature existing code that depends on the
default behavior of Float should be fine.
It would be nice if Ruby had this type of thing built-in to those
commands, though.
-Michael Libby
···
On Sun, 2004-06-27 at 09:58, Todd Gardner wrote:
David Garamond <lists@zara.6.isreserved.com> wrote in message news:<40DE9C9F.3030204@zara.6.isreserved.com>...
> class Float
> def round_n(n=0)
> raise FloatDomainError unless self.finite?
> raise ArgumentError unless n.class == Fixnum && n >= 0
> sprintf("%.#{n}f", self).to_f
> end
>
> def ceil_n(n=0)
> raise FloatDomainError unless self.finite?
> raise ArgumentError unless n.class == Fixnum && n >= 0
> (self*10**n).ceil.to_f / 10**n
> end
>
> def floor_n(n=0)
> raise FloatDomainError unless self.finite?
> raise ArgumentError unless n.class == Fixnum && n >= 0
> (self*10**n).floor.to_f / 10**n
> end
> end
>
> However I can't help get the feeling that Ruby already has something
> like this. Did I indeed miss it?
class Float
def round_n(n=0)
raise FloatDomainError unless self.finite?
raise ArgumentError unless n.class == Fixnum && n >= 0
sprintf("%.#{n}f", self).to_f
end
def ceil_n(n=0)
raise FloatDomainError unless self.finite?
raise ArgumentError unless n.class == Fixnum && n >= 0
(self*10**n).ceil.to_f / 10**n
end
def floor_n(n=0)
raise FloatDomainError unless self.finite?
raise ArgumentError unless n.class == Fixnum && n >= 0
(self*10**n).floor.to_f / 10**n
end
end
That's the same technique he's using for ceil and floor-- seems like the
best approach available (the only thing left to do now is test whether
multiply and divide is faster than sprintf). Except that instead of
defining round_n, ceil_n, and floor_n, I would probably just redefine
the existing Float#round, Float#ceil and Float#floor methods. Because
he's got n=0 in the method signature existing code that depends on the
default behavior of Float should be fine.
Btw, if you want to override #round, #ceil, #floor, remember to return a Fixnum if n=0 to avoid breaking other code.