Python 2.6.6 中的小数和科学计数法问题
我在处理十进制值时遇到困难,在某些情况下需要将其用于算术,而在其他情况下则需要将其用作字符串。具体来说,我有一个速率列表,例如:
rates=[0.1,0.000001,0.0000001]
我使用它们来指定图像的压缩率。我最初需要将这些值作为数字,因为我需要能够对它们进行排序以确保它们按特定顺序排列。我还希望能够将每个值转换为字符串,这样我就可以 1) 将费率嵌入到文件名中,2) 将费率和其他详细信息记录在 CSV 文件中。第一个问题是任何超过 6 位小数的浮点数在转换为字符串时都是科学格式:
>>> str(0.0000001)
'1e-07'
所以我尝试使用 Python 的 Decimal 模块,但它也将一些浮点数转换为科学记数法(似乎与我读过的文档相反) )。例如:
>>> Decimal('1.0000001')
Decimal('1.0000001')
# So far so good, it doesn't convert to scientific notation with 7 decimal places
>>> Decimal('0.0000001')
Decimal('1E-7')
# Scientific notation, back where I started.
我也按照多篇文章中的建议研究了字符串格式,但我没有任何运气。任何建议和指示都会受到这位 Python 新手的赞赏。
I'm having difficulty with decimal values that I need to use for arithmetic in some cases and as strings in others. Specifically I have a list of rates, ex:
rates=[0.1,0.000001,0.0000001]
And I am using these to specify the compression rates for images. I need to initially have these values as numbers because I need to be able to sort them to make sure they are in a specific order. I also want to be able to convert each of these values to strings so I can 1) embed the rate into the filename and 2) log the rates and other details in a CSV file. The first problem is that any float with more than 6 decimal places is in scientific format when converted to a string:
>>> str(0.0000001)
'1e-07'
So I tried using Python's Decimal module but it is also converting some floats to scientific notation (seemingly contrary to the docs I've read). Ex:
>>> Decimal('1.0000001')
Decimal('1.0000001')
# So far so good, it doesn't convert to scientific notation with 7 decimal places
>>> Decimal('0.0000001')
Decimal('1E-7')
# Scientific notation, back where I started.
I've also looking into string formatting as suggested in multiple posts, but I've not had any luck. Any suggestions and pointers are appreciated by this Python neophyte.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
然后您必须指定字符串格式:
这将产生
['0.10000000', '0.00000100', '0.00000010']
。也适用于Decimal
。You have to specify the string format then:
This yields
['0.10000000', '0.00000100', '0.00000010']
. Works withDecimal
, too.以上应该对你有用
The above should work for you
请参阅
% 格式
,尤其是浮动点换算:示例,使用
f
格式。您还可以使用较新的(从 2.6 开始)
str.format()
方法:See
% formatting
, especially the floating point conversions:An example, using
f
format.You can also use the newer (starting 2.6)
str.format()
method:使用 f 字符串:
字符串格式
{r:.7f}
表示小数点后使用的位数,在本例中为 7。Using f-strings:
The string format
{r:.7f}
indicates the number of digits used after the decimal point, which in this case is 7.