P i
P i

Reputation: 30714

Decimal.getcontext.prec() fails to enforce precision

In [1]: from decimal import Decimal, getcontext

In [2]: getcontext().prec = 4

In [3]: Decimal('0.12345')
Out[3]: Decimal('0.12345')

In [4]: Decimal('0.12345') * Decimal('0.12345')
Out[4]: Decimal('0.01524')

I was expecting '0.1234' and '0.0152' for the second.

Is there a way to achieve this?

Upvotes: 0

Views: 761

Answers (1)

AKX
AKX

Reputation: 169318

It's there in the Decimal FAQ:

Q. I noticed that context precision is applied to the results of operations but not to the inputs. Is there anything to watch out for when mixing values of different precisions?

A. [...] The solution is either to increase precision or to force rounding of inputs using the unary plus operation.

>>> from decimal import Decimal, getcontext
>>> getcontext().prec = 4
>>> +Decimal('0.12345')
Decimal('0.1234')
>>> (+Decimal('0.12345') * +Decimal('0.12345'))
Decimal('0.01523')
>>>

Upvotes: 4

Related Questions