Skip to content

Instantly share code, notes, and snippets.

@bcardarella
Created September 11, 2009 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bcardarella/185644 to your computer and use it in GitHub Desktop.
Save bcardarella/185644 to your computer and use it in GitHub Desktop.
Float#round_to_faction
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