【发布时间】:2017-04-03 11:48:29
【问题描述】:
我正在尝试在 Python 2.7.10 中解决我的代码中的一些浮点问题。在测试时,我遇到了 format 方法的奇怪行为:
print "{}".format(0.3000000000004) # 13 decimals
打印:0.3
但是:
print "{}".format(0.300000000004) # 12 decimals
打印:0.300000000004
既然我没有指定格式,为什么它会四舍五入第一个数字?是否有默认允许的小数位数?
【问题讨论】:
-
您只是看到默认的
str()转换格式为12 位小数,而repr()显示更多。 -
行为在 Python 3(至少 3.6)中有所不同
-
@Chris_Rands:是的,精度已更改。
-
@Chris_Rands: Why does str(float) return more digits in Python 3 than Python 2? 用于 Py 2 与 3 的更改。
-
@Chris_Rands:深入解释使用
str()与repr()时的格式:Precision of repr(f), str(f), print(f) when f is float
标签: python floating-point numbers format