Wednesday, July 23, 2008

Ruby: Floating point round off

my method of doing this as

def round(float, decimal_places) # By Jagan Reddy
exponent = decimal_places + 2
@float = float*(10**exponent)
@float = @float.round
@float = @float / (10.0**exponent)
end

In short we can also do this way
class Float
def round_to(i)
(self * 10**i).round.to_f / 10**i
end
end
value = 1328.3337
value.round_to(3)
=>1328.334

No comments: