小编tri*_*tab的帖子

Python 2.6.6中的小数和科学记数法的问题

我在使用十进制值时遇到困难,在某些情况下需要用于算术,而在其他情况下则需要用作字符串.具体来说,我有一个费率列表,例如:

rates=[0.1,0.000001,0.0000001]
Run Code Online (Sandbox Code Playgroud)

我正在使用它们来指定图像的压缩率.我需要最初将这些值作为数字,因为我需要能够对它们进行排序以确保它们按特定顺序排列.我还希望能够将这些值中的每一个转换为字符串,以便我可以1)将速率嵌入到文件名中,2)将速率和其他详细信息记录在CSV文件中.第一个问题是,当转换为字符串时,任何超过6位小数的浮点数都是科学格式:

>>> str(0.0000001)
'1e-07'
Run Code Online (Sandbox Code Playgroud)

所以我尝试使用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.
Run Code Online (Sandbox Code Playgroud)

我也在调查多个帖子中建议的字符串格式,但我没有运气.任何建议和指针都受到这个Python新手的赞赏.

python string scientific-notation decimal

2
推荐指数
2
解决办法
6466
查看次数

标签 统计

decimal ×1

python ×1

scientific-notation ×1

string ×1