简体   繁体   中英

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?

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')
>>>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM