Created
June 29, 2011 13:42
-
-
Save semmons99/1053857 to your computer and use it in GitHub Desktop.
bankers rounding
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
def round(n) | |
cents = n * BigDecimal("100") | |
remainder = cents % BigDecimal("1") | |
if remainder == BigDecimal("0") | |
n | |
elsif remainder < BigDecimal("0.5") | |
n.round(2, BigDecimal::ROUND_DOWN) | |
elsif remainder > BigDecimal("0.5") | |
n.round(2, BigDecimal::ROUND_UP) | |
elsif cents.even? | |
n.round(2, BigDecimal::ROUND_DOWN) | |
else | |
n.round(2, BigDecimal::ROUND_UP) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment