知道为什么 Python 的decimal
模块不喜欢数字 1 或更多,而是 0.9 或更少吗?
>>> import decimal
>>> max_digits = 5
>>> decimal_places = 5
>>> context = decimal.getcontext().copy()
>>> context.prec = max_digits
1 本身的数字太多:
>>> value = decimal.Decimal('1')
>>> '%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/decimal.py", line 2470, in quantize
'quantize result has too many digits for current context')
File "/usr/lib/python2.7/decimal.py", line 3872, in _raise_error
raise error(explanation)
decimal.InvalidOperation: quantize result has too many digits for current context
但任何低于 1 的都可以:
>>> value = decimal.Decimal('0.9')
>>> '%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))
'0.90000'
有人愿意解释吗?