>>> from decimal import Decimal, ROUND_HALF_UP, setcontext, Context >>> ctx = Context(prec=2, rounding=ROUND_HALF_UP) >>> setcontext(ctx) >>> total = Decimal('0.002') + Decimal('0.002') >>> total Decimal('0.004')
It actually does not round automatically, as I expected, so I can not use it for the entire block of calculations.
Another problem: intermediate values ββare rounded, which loses accuracy.
from decimal import Decimal, ROUND_HALF_UP, getcontext, setcontext, Context class FinanceContext: def __enter__(self): self.old_ctx = getcontext() ctx = Context(prec=2, rounding=ROUND_HALF_UP) setcontext(ctx) return ctx def __exit__(self, type, value, traceback): setcontext(self.old_ctx) class Cart(object): @property def calculation(self): with FinanceContext(): interim_value = Decimal('1') / Decimal('3') print interim_value, "prints 0.33, lost precision due to new context"
source share