Python 2.6.6中的小数和科学计数法问题 [英] Problems with decimals and scientific notation in Python 2.6.6

查看:391
本文介绍了Python 2.6.6中的小数和科学计数法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我难以使用十进制值进行算术运算,而在其他情况下,则需要将其用作字符串。具体来说,我有一个费率列表,例如:

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]

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

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'

所以我尝试使用Python的Decimal模块但它还将一些浮点数转换为科学计数法(似乎与我阅读的文档相反)。例如:

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.

我也按照多篇文章中的建议研究字符串格式,但是我没有任何内容运气。这个Python新手会赞赏任何建议和指针。

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.

推荐答案

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

You have to specify the string format then:

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

这将产生 ['0.10000000','0.00000100','0.00000010'] 。也可以使用十进制

This yields ['0.10000000', '0.00000100', '0.00000010']. Works with Decimal, too.

这篇关于Python 2.6.6中的小数和科学计数法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆