Last active
December 18, 2015 09:28
-
-
Save hernan/5761110 to your computer and use it in GitHub Desktop.
round down a float
This file contains 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 | |
def round_down n=0 | |
s = self.to_s | |
l = s.index('.') + 1 + n | |
s.length <= l ? self : s[0,l].to_f | |
end | |
end | |
# 2nd variant | |
class Float | |
def round_down n=0 | |
n < 1 ? self.to_i.to_f : (self - 0.5 / 10**n).round(n) | |
end | |
end | |
# 3rd variant | |
# from http://www.hans-eric.com/code-samples/ruby-floating-point-round-off/ | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment