Created
June 7, 2012 16:27
-
-
Save Tronix117/2889881 to your computer and use it in GitHub Desktop.
MonkeyPatch roundHalfToEven (Banker round)
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
## | |
# MonkeyPatch roundHalfToEven (Banker round) | |
# | |
# Solve most of floating binary point problems, and round | |
# to the specified decimal using banker round for financial | |
# calculations. Half fraction between number are rounded to | |
# the nearest even number. | |
# | |
# @author Jeremy Trufier <[email protected]> | |
# @copyright Storific 2012 | |
## | |
class Float | |
def roundHalfToEven(d = 0) | |
d = 10 ** d | |
n = self * d | |
t = n.to_i | |
f = (n - t).abs | |
return t.to_f / d if f < 0.5 || f === 0.5 && t % 2 === 0 | |
return (t + (self/self.abs).to_i).to_f / d | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment