Python Decimal() | decimal.InvalidOperation

Viewed 1202

I'd like to overcome an issue with Decimal that i am encountering while migrating from python 2 to 3.

Python 2.7:

>>> Decimal('333').quantize(Decimal('.01'), rounding=decimal.ROUND_HALF_DOWN)
Decimal('333.00')

Python 3.7:

>>> Decimal('333').quantize(Decimal('.01'), rounding=decimal.ROUND_HALF_DOWN)
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

As the exemple show, there is a behavior change between those python version.

Did i miss something there ?

Any insight welcomed.

1 Answers

this append when the decimal.get_context().prec is lower than your expected round

Exemple :

In [3]: from decimal import Decimal

In [4]: Decimal('333').quantize(Decimal('.01'), rounding=decimal.ROUND_HALF_DOWN)
Out[4]: Decimal('333.00')

In [5]: decimal.getcontext()
Out[5]: Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])

In [6]: round(Decimal('333'), 2)
Out[6]: Decimal('333.00')

But if you do :

import decimal
In [11]: context = decimal.getcontext()
In [12]: context.prec = 1
In [13]: decimal.setcontext(context)
In [15]: Decimal('333').quantize(Decimal('.01'), rounding=decimal.ROUND_HALF_DOWN)
---------------------------------------------------------------------------
InvalidOperation                          Traceback (most recent call last)
<ipython-input-15-24094f7b9eb1> in <module>
----> 1 Decimal('333').quantize(Decimal('.01'), rounding=decimal.ROUND_HALF_DOWN)

InvalidOperation: [<class 'decimal.InvalidOperation'>]

So keep in mind that your context.precision need to be greater or equal of your rounding needs

Related