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
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…
Second reply to the second copy of this identical post. This is not a
good
idea. The problem is that Ruby’s numbers are stored internally in binary
form, and this multiply – truncate – divide process will not work as
intended for a lot of numbers.
It is better to retain the full resolution of binary numbers internally,
and
simply print the number with the desired number of decimal places:
#!/usr/bin/ruby -w
0.upto(10) do
n = rand() * 100
printf("%5.02f\n",n)
end