Home > Net >  python decimal rounding issue
python decimal rounding issue

Time:10-13

>>> round((611.05/10.0),2)
61.1
>>> round((611.05/10.0),3)
61.105

How can I get 61.11 ?

I tried with following but results are same

>>> ctx = decimal.getcontext()
>>> ctx.rounding = decimal.ROUND_HALF_UP

CodePudding user response:

The decimal context is applied to decimal calculations:

from decimal import Decimal, ROUND_HALF_UP

non_rounded = Decimal("611.05")/Decimal("10.0")
non_rounded.quantize(Decimal(".01"), rounding=ROUND_HALF_UP)

Returns

Decimal('61.11')

EDIT: using quantize instead of round reference

  • Related