四舍五入函数round()在刚好0.5时的小坑

python中的四舍五入函数round(),当保留位数的后面那一位数刚好是5时,python2是,python3是

Python2中round(0.5)结果是1

$python
Python 2.7.5 (default, Jun 20 2023, 11:36:40) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> round(0.5)
1.0

Python3中round(0.5)结果是0

$python3
Python 3.12.2 (main, Mar  7 2024, 14:42:49) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> round(0.5)
0

现在一般都是使用python3了,所以当数字刚好是0.5的时候(=0.5),会

但是如果5的后面还有数字(>0.5,比如0.51),就不 了,还是

下面是举例:

print("0.4 -> " + str(round(0.4)))
print("0.5 -> " + str(round(0.5)))
print("0.50 -> " + str(round(0.50)))
print('0.501 -> ' + str(round(0.501)))
print("0.51 -> " + str(round(0.51)))
print("0.6 -> " + str(round(0.6)))

输出:

0.4 -> 0
0.5 -> 0
0.50 -> 0
0.501 -> 1
0.51 -> 1
0.6 -> 1

结论

<=0.5时,比如0.2、0.4、0.5时,结果是,为0。

>0.5时,比如0.51、0.6、0.8时,结果是,为1。


Last modified on 2024-03-29

- CATALOG -