我正在尝试读取财务数据并将其存储。我从那里获得财务数据的地方以惊人的精度存储了数据,但是我只对小数点后的5位数字感兴趣。因此,我决定在我创建的Decimal上使用t = .quantize(cdecimal.Decimal('。00001'),rounding = cdecimal.ROUND_UP),但始终收到InvalidOperation异常。为什么是这样?

>>> import cdecimal
>>> c = cdecimal.getcontext()
>>> c.prec = 5
>>> s = '45.2091000080109'
>>> # s = '0.257585003972054' works!
>>> t = cdecimal.Decimal(s).quantize(cdecimal.Decimal('.00001'), rounding=cdecimal.ROUND_UP)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  cdecimal.InvalidOperation: [<class 'cdecimal.InvalidOperation'>]

为什么这里有无效的操作?如果我将精度更改为7(或更高),它将起作用。如果我将s设置为'0.257585003972054'而不是原始值,那也可以!到底是怎么回事?

谢谢!

最佳答案

十进制版本提供了对该错误的更好描述:

Python 2.7.2+ (default, Feb 16 2012, 18:47:58)
>>> import decimal
>>> s = '45.2091000080109'
>>> decimal.getcontext().prec = 5
>>> decimal.Decimal(s).quantize(decimal.Decimal('.00001'), rounding=decimal.ROUND_UP)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/decimal.py", line 2464, in quantize
    'quantize result has too many digits for current context')
  File "/usr/lib/python2.7/decimal.py", line 3866, in _raise_error
    raise error(explanation)
decimal.InvalidOperation: quantize result has too many digits for current context
>>>
Docs:

但是我必须承认我不知道这意味着什么。

09-30 18:39