Floating point round off
With a little monkey patching we can add custom round off methods to the Float class.
1 2 class Float 3 def round_to(x) 4 (self * 10**x).round.to_f / 10**x 5 end 6 7 def ceil_to(x) 8 (self * 10**x).ceil.to_f / 10**x 9 end 10 11 def floor_to(x) 12 (self * 10**x).floor.to_f / 10**x 13 end 14 end
Example usage:
num = 138.249
num.round_to(2)
# => 138.25
num.floor_to(2)
# => 138.24
num.round_to(-1)
# => 140.0