[英]Python Decimal to string produces strange scientific notation
I am dealing with a bug where applying the str
function to an instance of decimal.Decimal
gives me the string '0E-1000'
. 我正在处理一个错误,将
str
函数应用于decimal.Decimal
的实例给我字符串'0E-1000'
。 I expected that str
applied to a Decimal
would always give me a string of the form -?[0-9]+(\\.[0-9]+)
, which is what I want. 我期望应用于
Decimal
str
总是会给我一个字符串-?[0-9]+(\\.[0-9]+)
,这就是我想要的。
Firstly, if I understand correctly, the scientific notation '0E-1000'
represents 0 x 10^-1000, ie zero. 首先,如果我理解正确,科学记数法
'0E-1000'
代表0 x 10 ^ -1000,即零。 Why am I getting this particular representation of zero? 为什么我得到零的特定表示? Why not
'0E-42'
, which is the same? 为什么不
'0E-42'
,这是一样的?
Secondly, I cannot manually construct a Decimal
which reproduces this bug. 其次,我不能手动构造一个重现这个bug的
Decimal
。 The buggy Decimal
instance comes from an external source. 有缺陷的
Decimal
实例来自外部源。 The expression str(Decimal(0))
evaluates to '0'
in the REPL. 表达式
str(Decimal(0))
在REPL中的计算结果为'0'
。 How can I construct an instance d
of Decimal
for which str(d)
evaluates to '0E-1000'
? 如何构造一个
Decimal
的实例d
,其中str(d)
计算结果为'0E-1000'
?
EDIT: Thirdly, how can I convert an arbitrary Decimal
instance to a string in, you know, decimal notation? 编辑:第三,如何将任意
Decimal
实例转换为字符串,你知道, 十进制表示法?
If you want to reproduce your decimal, just construct it from the string: 如果要重现小数,只需从字符串构造它:
>>> d=decimal.Decimal("0E-1000")
>>> str(d)
'0E-1000'
I believe the difference is the difference between 0
and 0.00000
(or in your case 1000 zeros), which is the accuracy. 我相信差异是
0
到0.00000
之间的差异(或者在你的情况下是1000个零),这就是准确性。 This could be significant in scientific situations, where rounding etc. is controlled by the precision of the operands. 这在科学情况下可能是重要的,其中舍入等由操作数的精度控制。 If you want to make printing consistent, use
decimal.Decimal.normalize
: 如果要使打印一致,请使用
decimal.Decimal.normalize
:
>>> d=decimal.Decimal("0E-1000")
>>> d
Decimal('0E-1000')
>>> d.normalize()
Decimal('0')
>>> str(d.normalize())
'0'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.