Python float - str - 漂浮奇怪 [英] Python float - str - float weirdness

查看:131
本文介绍了Python float - str - 漂浮奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 >>> float(str(0.65000000000000002))

0.65000000000000002

>>> float(str(0.47000000000000003))

0.46999999999999997 ???

这是怎么回事?
如何将 0.47000000000000003 转换为字符串,并将结果值转换为浮点数?



Python 2.5.4在Windows上。

解决方案

str(0.47000000000000003) give '0.47' float('0.47')可以是 0.46999999999999997
这是由于浮点数的表示方式(见维基百科文章)注意: float(repr(0.47000000000000003))或者 eval(repr(0.47000000000000003)) )会给你预期的结果,但你应该使用 Decimal 如果你需要精确度。


>>> float(str(0.65000000000000002))

0.65000000000000002

>>> float(str(0.47000000000000003))

0.46999999999999997     ???

What is going on here? How do I convert 0.47000000000000003 to string and the resultant value back to float?

I am using Python 2.5.4 on Windows.

解决方案

str(0.47000000000000003) give '0.47' and float('0.47') can be 0.46999999999999997. This is due to the way floating point number are represented (see this wikipedia article)

Note: float(repr(0.47000000000000003)) or eval(repr(0.47000000000000003)) will give you the expected result, but you should use Decimal if you need precision.

这篇关于Python float - str - 漂浮奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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