0
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?

P i
  • 29,020
  • 36
  • 159
  • 267
  • isn't `prec` the number of significant digits? – hiro protagonist Mar 22 '21 at 16:28
  • [`quantize`](https://docs.python.org/3/library/decimal.html#decimal.Decimal.quantize) should work for you. – hiro protagonist Mar 22 '21 at 16:30
  • This is two different issues; the first is that the context doesn't apply to a newly-constructed Decimal object, only to the results of arithmetic operations (so e.g. `+Decimal('0.12345')` behaves how you expect); the second is that `prec` is the number of significant digits, not the number of decimal places. Please see [Why doesn't decimal.getcontext().prec=3 work for decimal.Decimal(1.234)](https://stackoverflow.com/q/58781495/12299000) and [Why Python getcontext().prec = 4 sometimes gives 3 decimals instead of 4?](https://stackoverflow.com/q/28094459/12299000) – kaya3 Mar 22 '21 at 16:38

1 Answers1

4

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')
>>>
AKX
  • 152,115
  • 15
  • 115
  • 172