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
I’m generally opposed to monkey-patching, but in this case, why not? Thanks for this post.
@Daniel Rosenstark
Like all powerful tools one should not overuse it. Thanks for your comment.
can i know where to add this patching
Thanks, this was handy! I wonder why it’s not included in the core?