python - 为什么 Decimal(0) 的科学格式与 float 0 不同?

标签 python python-3.x formatting decimal

使用时 Decimal(0)并将其格式化为 .2e格式化发生以下情况:

>>> f'{Decimal(0):.2E}'
'0.00E+2'
但是,如果您只是使用 00.发生以下情况:
>>> 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/

相关文章:

python - 如何将矢量场限制在一定半径的圆上?

python - 从 Dicts Python 3 中去除换行符

python - 为什么不切换到 Python 3.x?

c# - 在 Resharper 中为对象和数组初始化程序获取正确的缩进

python - 在 python 中将 .csv 文件打印为列表

javascript - "dependent drop down list"不起作用 [Google App Engine 上的 Flask]

python-3.x - Swagger/ flask : how to handle query parameters with dashes

python - 在单独的线程上从大文件插入文本时 tk UI 挂起

c# - 在 C# 中格式化日期/时间

java - &nbsp 字符在 Java 中无法正确显示