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

    xiaoxiao2021-04-14  46

    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 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模块

    转载请注明原文地址: https://ju.6miu.com/read-669928.html

    最新回复(0)