考虑以下Python3的片段。(Python 3.7.7 on mac os catalina)
>>> from decimal import Decimal as d
>>> zero = d('0')
>>> one = d('1')
>>> for q in range(10):
... one.quantize(d('10') ** -q)
...
Decimal('1')
Decimal('1.0')
Decimal('1.00')
Decimal('1.000')
Decimal('1.0000')
Decimal('1.00000')
Decimal('1.000000')
Decimal('1.0000000')
Decimal('1.00000000')
Decimal('1.000000000')
>>> for q in range(10):
... zero.quantize(d('10') ** -q)
...
Decimal('0')
Decimal('0.0')
Decimal('0.00')
Decimal('0.000')
Decimal('0.0000')
Decimal('0.00000')
Decimal('0.000000')
Decimal('0E-7')
Decimal('0E-8')
Decimal('0E-9')
为什么此时带零的量化会变成E的符号? 为什么它与其他数字不一致? 我又该如何控制它?
注意:如果我使用内置的 round
函数而不是 quantize
这让我猜测 round
电话 quantize
当它得到一个十进制数时。
由于我想要带尾数为0的字符串,我能想到的最好的变通方法是写我自己的 _round()
功能。
def _round(s, n):
if decimal.Decimal(s).is_zero():
return '0.' + '0' * n
return decimal.Decimal(s).quantize(decimal.Decimal(10) ** -n)
但这似乎有点蹩脚。 而且无论如何,我想了解 何以 Decimal.quantize
的行为是这样的。
回答我自己的问题,暂且不说 何以 Python3 Decimal
有这样的行为,控制格式的方法是不要去搞乱 quantize
根本没有。 在这里,我们使用 format
,如是。 (同上) zero
和 one
为小数)
>>> for q in range(10):
... '{:.{n}f}'.format(zero, n=q)
...
'0'
'0.0'
'0.00'
'0.000'
'0.0000'
'0.00000'
'0.000000'
'0.0000000'
'0.00000000'
'0.000000000'
>>> for q in range(10):
... '{:.{n}f}'.format(one, n=q)
...
'1'
'1.0'
'1.00'
'1.000'
'1.0000'
'1.00000'
'1.000000'
'1.0000000'
'1.00000000'
'1.000000000'
在此感谢评论的有益指点。