Bernard Kenik
12/5/2006 10:16:00 PM
You can use the number.round method, but this doesn't take a number of
decimal places.
To round 1.234 to 1.23 use this code:
x = 1.234
x = x * 100 # -> 123.4
x = x.round -> 123
x = x / 100.0 => 1.23
At least, that's the best method I can find from the Ruby docs...
Dan
Li Chen wrote:
Hi all,
I have a number, for example, 1.123456789. What is the Ruby way to
change it into whatever number of floating points such as 1.12,
1.123,1.1234568 or 1.12345679.
Thanks,
Li
class Float
def places(places)
(self * 10 ** places).truncate / 10.0 ** places
end
end
1.123456789.places(5) => 1.12345
you can use round instead of truncate if you want to round off
alternate method
class Float
def place(places)
sprintf("%0.#{places}f", self).to_f
end
end
not sure which method is most efficient