-
-
Save jamesarosen/287823 to your computer and use it in GitHub Desktop.
Float#round_to_precision
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Float | |
# Takes a fraction and will round a float to the nearest multiple | |
# >> k = 0.4 | |
# >> k.round_to_fraction | |
# => 0.5 | |
# >> k = 0.75 | |
# >> k.round_to_fraction | |
# => 1.0 | |
# >> k.round_to_fraction(0.65) | |
# => 0.65 | |
def round_to_fraction(fraction = 0.5) | |
if fraction >= 1.0 | |
raise "fraction must be below 1.0" | |
elsif fraction > 0.5 | |
num = 2 | |
else | |
num = (1 / fraction).to_i | |
end | |
modifier = 0.0 | |
(1..num).each do |n| | |
mod_difference = ((modifier + self.to_i) - self).abs | |
if num == n | |
difference = ((1.0 + self.to_i) - self).abs | |
else | |
difference = (((n * fraction) + self.to_i) - self).abs | |
end | |
if difference <= mod_difference | |
if num == n | |
modifier = 1.0 | |
else | |
modifier = fraction * n | |
end | |
end | |
end | |
self.to_i + modifier | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment