为什么 Decimal(0) 的科学格式与 float 0 不同?
Why is the scientific formatting of Decimal(0) different from float 0?
当使用 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')
当使用 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')