Skip to content

Instantly share code, notes, and snippets.

@Tronix117
Created June 7, 2012 16:27
Show Gist options
  • Save Tronix117/2889881 to your computer and use it in GitHub Desktop.
Save Tronix117/2889881 to your computer and use it in GitHub Desktop.
MonkeyPatch roundHalfToEven (Banker round)
##
# 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