-
Rounding a Float to a Fraction
10 October 2009I had a need for more rounding precision than the regular Ruby Float#round method. For example, if I wanted to round to the nearest half Ruby does:
>> (0.6).round
=> 1
What I needed was:
>> (0.6).round_to_fraction(0.5)
=> 0.5
So I wrote up this monkey patch for the Float class:
Float#round_to_fraction(fraction = 0.5)
This works with any fractional value:
>> (0.75).round_to_fraction(0.65)
=> 0.65
My use case was to round out distance values. I wanted to round to nearest quarter mile values.