Python Notes: Money Rounding Demo (for GAAP)
- The information presented here is intended for educational use.
- The information presented here is provided free of charge, as-is, with no warranty of any kind.
- Edit: 2022-05-21
Money Rounding Demo (for GAAP)
#!/bin/python3
# ====================================================
# title : money_rounding_demo.py
# author : Neil Rieck
# created: 2202-05-13
# notes :
# 1) a few hacks to test out rounding schemes for GAAP
# (Generally Accepted Accounting Principles)
# 2) decimal.Decimal is more accurate than float
# ====================================================
#
from decimal import Decimal, ROUND_HALF_UP
D = Decimal
print("money_rounding_demo.py")
#
# program constants (first hack)
# note: unpredictable because .01 is a float?
#
cents = D(.01) # not exactly what I wanted
print(f"D(.01) = {cents}")
#
# program constants (take 2)
#
cents = D('.01') # exactly what I wanted
print(f"D('.01') = {cents}")
d100 = D('100.00') # use for divide by 100
d60 = D('60.00') # use for divide by 60
tiny = D('.001') # use for experiments
#
# a little stub to round up (or truncate down)
#
def money_round(x):
return x.quantize(cents, ROUND_HALF_UP)
#
print("\ntest 1 (success)")
accum = D('1.23')
print(f"accum after init: {accum}")
#
for x in range(0, 10):
accum += tiny
hack = money_round(accum)
print(f"accum {accum} hack {hack}")
#
print("\ntest 2 (success)")
accum = D('123.00')
print(f"accum after init: {accum}")
#
for x in range(0, 10):
accum += tiny
hack = money_round(accum)
print(f"accum {accum} hack {hack}")
#
print("\ntest 3 (success)")
accum = D('123')
print(f"accum after init: {accum}")
accum = money_round(accum)
print(f"accum after rounding: {accum}")
#
# end
money_rounding_demo.py
D(.01) = 0.01000000000000000020816681711721685132943093776702880859375
D('.01') = 0.01
test 1 (success)
accum after init: 1.23
accum 1.231 hack 1.23
accum 1.232 hack 1.23
accum 1.233 hack 1.23
accum 1.234 hack 1.23
accum 1.235 hack 1.24
accum 1.236 hack 1.24
accum 1.237 hack 1.24
accum 1.238 hack 1.24
accum 1.239 hack 1.24
accum 1.240 hack 1.24
test 2 (success)
accum after init: 123.00
accum 123.001 hack 123.00
accum 123.002 hack 123.00
accum 123.003 hack 123.00
accum 123.004 hack 123.00
accum 123.005 hack 123.01
accum 123.006 hack 123.01
accum 123.007 hack 123.01
accum 123.008 hack 123.01
accum 123.009 hack 123.01
accum 123.010 hack 123.01
test 3 (success)
accum after init: 123
accum after rounding: 123.00
Links
Back to
Home
Neil Rieck
Waterloo, Ontario, Canada.