美文网首页Python 踩坑记
Round 的四舍五入问题

Round 的四舍五入问题

作者: Creator_蔚蓝 | 来源:发表于2018-09-17 21:22 被阅读179次
问题描述:

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

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

例如:
round(3.585,2) > 3.58

假如 第 n+1 位的数字 > 5,又能正常显示:
round(3.586,2) >3.59

原因解释:

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

相关文章

网友评论

    本文标题:Round 的四舍五入问题

    本文链接:https://www.haomeiwen.com/subject/pgwdnftx.html