Python 中的round函数

在python2.7的doc中,round()的最后写着,

"Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0." 

保留值将保留到离上一位更近的一端(四舍六入),如果距离两端一样远,则保留到离0远的一边。所以round(0.5)会近似到1,而round(-0.5)会近似到-1。



但是到了python3.5的doc中,文档变成了

"values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice." 

如果距离两边一样远,会保留到偶数的一边。比如round(0.5)和round(-0.5)都会保留到0,而round(1.5)会保留到2。

 

Python 2.7 中的结果如下:

>>> round(-0.5)
-1.0
>>> round(0.5)
1.0
>>> round(1.5)
2.0
>>> round(2.5)
3.0
>>> round(3.5)
4.0
>>> round(4.5)
5.0
>>> round(6.5)
7.0

 

Python 3.8 中的结果如下:

round(-0.5)
0
round(0.5)
0
round(1.5)
2
round(2.5)
2
round(3.5)
4
round(4.5)
4
round(5.5)
6
round(6.5)
6

 

===================================

round(number, digits)
参数:
    digits>0,四舍五入到指定的小数位
    digits=0, 四舍五入到最接近的整数
    digits<0 ,在小数点左侧进行四舍五入
    如果round()函数只有number这个参数,等同于digits=0

四舍五入规则:
    要求保留位数的后一位<=4,则不进位,如 round(5.214, 2)   保留小数点后两位,结果是 5.21
    要求保留位数的后一位“=5”,且该位数后面没有数字,向偶数靠拢,如 round(5.215, 2),结果为5.21
    要求保留位数的后一位“=5”,且该位数后面有数字,则进位,如 round(5.2151, 2),结果为5.22
    要求保留位数的后一位“>=6”,则进位。如  round(5.216, 2),结果为5.22


参考链接:https://blog.csdn.net/qq_34035425/article/details/123237006

 

=================================

>>> [round(x+0.555,2) for x in range(0,15)]
[0.56, 1.56, 2.56, 3.56, 4.55, 5.55, 6.55, 7.55, 8.55, 9.55, 10.55, 11.55, 12.55, 13.55, 14.55]
>>> round(1.555,2)
1.55

=================================

print( [x+0.555 for x in range(10)] )
[0.555, 1.5550000000000002, 2.555, 3.555, 4.555, 5.555, 6.555, 7.555, 8.555, 9.555]
print( [round(x+0.555,2) for x in range(10)] )
[0.56, 1.56, 2.56, 3.56, 4.55, 5.55, 6.55, 7.55, 8.55, 9.55]

=================================

 

posted @ 2021-08-26 14:55  emanlee  阅读(1449)  评论(0编辑  收藏  举报