关于python3中round()函数的四舍五入问题

来源:互联网 发布:淘宝千牛店铺名怎么改 编辑:程序博客网 时间:2024/09/21 08:57

round(float [,n])函数用于返回浮点数四舍五入后的值,小数点后保留n位(默认为0)

例如

>>round(3.5248,2)

>>3.52

但是有一个坑就是当保留n位时,第n+1位为数字5,此时它并不会进一位,而是舍弃掉。

例如

>>round(3.585,2)

>>3.58

这并不是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 resultof 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模块




0 0