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
  1. July 19th, 2009 at 15:04 | #1

    I’m generally opposed to monkey-patching, but in this case, why not? Thanks for this post.

  2. Hans-Eric Grönlund
    August 3rd, 2009 at 11:34 | #2

    @Daniel Rosenstark
    Like all powerful tools one should not overuse it. Thanks for your comment.

  3. uma mahes
    August 22nd, 2009 at 07:22 | #3

    can i know where to add this patching

  4. ben
    November 14th, 2009 at 17:42 | #4

    Thanks, this was handy! I wonder why it’s not included in the core?

  1. June 9th, 2009 at 15:15 | #1