Python 2.6.6中的小数和科学符号问题

2024-05-23 19:29:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在某些情况下,我很难处理需要用于算术的十进制值,而在其他情况下,则需要用作字符串。具体来说,我有一个价格表,例如:

rates=[0.1,0.000001,0.0000001]

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

>>> str(0.0000001)
'1e-07'

所以我尝试使用Python的Decimal模块,但它也将一些float转换为科学符号(似乎与我读过的文档相反)。例如:

>>> 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新手的赞赏。


Tags: 字符串图像排序速率格式情况数字科学
3条回答

请参阅^{},特别是浮点转换:

'e' Floating point exponential format (lowercase). (3)

'E' Floating point exponential format (uppercase). (3)

'f' Floating point decimal format. (3)

'F' Floating point decimal format. (3)

'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4)

'G' Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4)

例如,使用f格式。

>>> ["%10.7f" %i for i in rates]
[' 0.1000000', ' 0.0000010', ' 0.0000001']
>>> 

也可以使用较新的(从2.6开始)^{}方法:

>>> ['{0:10.7f}'.format(i) for i in rates]
[' 0.1000000', ' 0.0000010', ' 0.0000001']
>>> 

必须指定字符串格式,然后:

["%.8f" % (x) for x in rates]

这将产生['0.10000000', '0.00000100', '0.00000010']。也适用于Decimal

'{0:f}'.format(Decimal('0.0000001'))

上面的应该对你有用

相关问题 更多 >