python中round() 四舍五入

注意在Python3中 ,round()函数 并不是四舍五入,而是四舍六入五成双

五成双的意思是,高位为单数则进1凑成双数,高位为双数则不进位。 但是也不都是

如 ,最高位是4 双数 4.05 就不进位

num = 1
dd = round(4.050000190734863,num)
ss = round(4.05,num)
print(dd,ss,dd == ss) # 4.1 4.0 False

高位为单数则进1凑成双数  但是下面 5.05 保留一位 就变成了 5.0

num = 1
dd = round(5.050000190734863,num)
ss = round(5.05,num)
print(dd,ss,dd == ss) # 5.1 5.0 False

但是下面 9.05 保留一位 就变成了 9.1

num = 1
dd = round(9.050000190734863,num)
ss = round(9.05,num)
print(dd,ss,dd == ss) # 9.1 9.1 True

Python2中,round()的结果就是我们所理解的四舍五入,round(1.5)=2,round(2.5)=3。而Python3中,对round()函数有较大改动

但是这个不是bug

在python手册中这样说到:

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result
of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

简单来说,有些浮点数在计算机中并不能像整数那样被准确表达,它可能是近似值。因此就会出现这种问题,解决方法为decimal模块
 

猜你喜欢

转载自blog.csdn.net/weixin_37989267/article/details/114986510