python科学计数法保留小数,Python 2.6.6中的小数和科学计数法问题

python科学计数法保留小数,Python 2.6.6中的小数和科学计数法问题I’mhavingdifficultywithdecimalvaluesthatIneedtouseforarithmeticinsomecasesandasstringsinothers.SpecificallyIhavealistofrates,ex:rates=[0.1,0.000001,0.0000001]AndIamusing…

大家好,欢迎来到IT知识分享网。

python科学计数法保留小数,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]

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.

解决方案

You have to specify the string format then:

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

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

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/11050.html

(0)
上一篇 2024-03-26 13:15
下一篇 2024-03-26 19:45

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信