Created
February 19, 2015 23:27
-
-
Save br3nt/20f31fa906f387313013 to your computer and use it in GitHub Desktop.
Rounding values
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
# | |
# Rounds a number | |
# | |
# If nearest == pivot, the rounding will always go up. | |
# | |
# Default behaviour: | |
# round(0) # 10 | |
# round(1) # 10 | |
# round(9) # 10 | |
# round(10) # 20 | |
# round(19) # 20 | |
# round(20) # 30 | |
# round(99) # 100 | |
# round(100) # 200 | |
# round(101) # 200 | |
# round(999) # 1000 | |
# round(1000) # 2000 | |
# | |
def round(num, nearest = nil, pivot = nil) | |
negative = num < 0 # record if the number is negative | |
num = -num if negative # make the number positive | |
precision = Math.log10(num).to_i rescue 1 # are we dealing with 10's, 100's, 1000's... | |
precision = 1 if precision == 0 # the lowest value we want to round to is 10 | |
nearest ||= 10**precision # the rounding value | |
pivot ||= nearest # the value that will cause us to round up/down | |
# NOTE: if pivot == nearest, the rounding will always go up | |
result = (num + pivot) / nearest * nearest # perform the rounding | |
negative ? -result : result # make number negative, if required | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment