Skip to content

Instantly share code, notes, and snippets.

@semmons99
Created June 29, 2011 13:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save semmons99/1053857 to your computer and use it in GitHub Desktop.
Save semmons99/1053857 to your computer and use it in GitHub Desktop.
bankers rounding
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