Consider the following rounding approaches in decimal:
using quantize:
>>> (Decimal('1')/Decimal('3')).quantize(Decimal('0.00'), rounding=ROUND_HALF_UP)
Decimal('0.33')
using context:
>>> ctx = Context(prec=2, rounding=ROUND_HALF_UP)
>>> setcontext(ctx)
>>> Decimal('1')/Decimal('3')
Decimal('0.33')
Are there any actual differences between the 2 methods for rounding? Any gotchas? Is using the context a bit more elegant so that I can use with
statement for the whole calculation block?
>>> 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 would have expected, so I won't be able to use that for the whole calculation block.
Another problem, interim values are rounded which loses precision.
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"
# complex calculation using interim_value
final_result = ...
return final_result
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.