使用时 Decimal(0)
并将其格式化为 .2e
格式化发生以下情况:
>>> f'{Decimal(0):.2E}'
'0.00E+2'
但是,如果您只是使用 0
或 0.
发生以下情况:>>> f'{0.:.2E}'
'0.00E+00'
怎么结果不一样?
最佳答案
在我之前的回答中,我描述了 怎么样这是在 cpython 中完成的,在此我将描述 为什么 .
这个问题是在这个 discussion 中提出的大多数报价都来自那里:
让我们考虑一个例子:
>>> x = Decimal("1e+5").quantize(Decimal("1e+10"))
>>> x
Decimal('0E+10')
>>> s = "{:.19e}".format(x)
>>> s
'0.0000000000000000000e+29'
>>> Decimal(s)
Decimal('0E+10')
原始震级为e+10
, 格式化后还是 e+10
.原数的大小被保留 在格式化过程之后。
From the point of view of decimal it's the right thing. The original magnitude should be traceable
0
is really special in the IBM specification. The magnitude is kept, the precision is not.>>> Decimal("0e10") * Decimal("0e20") Decimal('0E+30') >>> Decimal("0.000e10") Decimal('0E+7')
So we're basically doing the reverse of the above in formatting when a precision is given.
因此,如果我们回到 OP 的原始示例:
>>> f'{Decimal(0):.2E}'
'0.00E+2'
如果返回 0.00Е+00
那么这个十进制数的大小将是 E-2
:>>> d = f'{Decimal(0):.2E}'
>>> d
'0.00E+2'
>>> Decimal(d)
Decimal('0')
>>> d = '0.00E+00'
>>> Decimal(d)
Decimal('0.00')
关于python - 为什么 Decimal(0) 的科学格式与 float 0 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63476471/