Ruby: Floating point round off

With a little monkey patching we can add custom round off methods to the Float class.

class Float
  def round_to(x)
    (self * 10**x).round.to_f / 10**x
  end

  def ceil_to(x)
    (self * 10**x).ceil.to_f / 10**x
  end

  def floor_to(x)
    (self * 10**x).floor.to_f / 10**x
  end
end

Example usage:

num = 138.249
num.round_to(2)
# => 138.25

num.floor_to(2)
# => 138.24

num.round_to(-1)
# => 140.0