Python 中的小数对象转换为科学记数法

Decimal object converting to scientific notation in Python

我已经通读了 Decimal 文档并研究了在 Python 中抑制科学记数法表达式的其他方法,但是我遇到了一个问题,即 Decimal 包没有按我预期的那样工作,我无法弄清楚如何获得我想要的输出。

我有一个字符串 - my_tick = "0.0000005"

type(my_tick)
<class 'str'>

当我将其传递给 Decimal() 时,对象被格式化并以科学记数法返回:

from decimal import *

formatted_tick = Decimal(my_tick)
print(formatted_tick)
5E-7

如果我调用 getcontext(),我会看到我的默认精度设置为小数点后 28 位:

getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[InvalidOperation, FloatOperation], traps=[InvalidOperation, DivisionByZero, Overflow])

我已经尝试将字符串包装为浮点数,但它仍然是 returns 科学记数法:

formatted_tick = Decimal(repr(float(my_tick)))
print(formatted_tick)
5E-7

两者都会产生值为 5E-7 的 Decimal 对象

对于我的函数,它必须保留一个值为0.0000005的小数对象,至于格式,我可能对其他数字有同样的问题,我不一定知道前面的精度时间,因此需要一个可以自行处理小数点后 1 到 10 位精度的本机解决方案。有谁知道当精度设置为 28 时 Decimal 为什么使用科学记数法?

提前谢谢你,

str.format 将按照您想要的方式格式化您的号码,如果您指定它应输出为 float:f,如下所示:

>>> "{:f}".format(decimal.Decimal("0.0000000005"))
"0.0000000005"

如果您希望此行为成为小数的默认字符串表示行为,您可以像这样定义 class:

 class NoScientificNotation(decimal.Decimal):
     def __str__(self):
         return "{:f}".format(self)

然后像 `Decimal:

一样使用它
>>> NoScientificNotation("0.0000000005")
Decimal('0.0000000005')

没有问题。