問題描述
>>> float(str(0.65000000000000002))
0.65000000000000002
>>> float(str(0.47000000000000003))
0.46999999999999997 ???
這里發生了什么?如何將 0.47000000000000003
轉換為字符串并將結果值轉換回浮點數?
What is going on here?
How do I convert 0.47000000000000003
to string and the resultant value back to float?
我在 Windows 上使用 Python 2.5.4.
I am using Python 2.5.4 on Windows.
推薦答案
str(0.47000000000000003)
給 '0.47'
和 float('0.47')
可以是 0.46999999999999997
.這是由于浮點數的表示方式(參見這篇 wikipedia 文章)
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)
注意:float(repr(0.47000000000000003))
或 eval(repr(0.47000000000000003))
會給你預期的結果,但你應該使用 十進制,如果你需要精確的話.
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 - 浮動怪異的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!