我对 Python 中的舍入方式有点困惑。
请问有人能够解释一下为什么 Python 的行为会像这样吗?
示例:
>>> round(0.05,1) # this makes sense
0.1
>>> round(0.15,1) # this doesn't make sense! Why is the result not 0.2?
0.1
同样适用于:
>>> round(0.25,1) # this makes sense
0.3
>>> round(0.35,1) # in my opinion, should be 0.4 but evaluates to 0.3
0.3
编辑: 总的来说,Python 有可能将数字向下取整,而不是向上取整。那么我是否可以理解,唯一可能发生的“异常”就是 Python 向下取整?或者它也可能因为存储方式而出现“异常”向上取整吗?(我还没有遇到过 Python 在我预期向下取整时向上取整的情况)
print '%.20f %.20f %.20f'%(.15, .25, .35)
- Robᵩhttp://stackoverflow.com/users/8747/rob%E1%B5%A9
- 一些浏览器如Chrome会在URL栏中呈现转义的Unicode字符。 - Galaxround(1.25, 1)
将给出1.3
,而在 Python 3 中它会给出1.2
。 - Mark Dickinson