美文网首页
Python3 - 数字的四舍五入

Python3 - 数字的四舍五入

作者: 惑也 | 来源:发表于2018-12-19 23:13 被阅读43次

问题

对浮点数执行指定精度的舍入运算。

解决方案

对于简单的舍入运算,使用内置的 round(value, ndigits) 函数即可。比如:

print(round(1.23, 1))
print(round(1.27, 1))
print(round(-1.27, 1))
print(round(3.1415, 3))

1.2
1.3
-1.3
3.142

传给 round() 函数的 ndigits 参数可以是负数,这种情况下, 舍入运算会作用在十位、百位、千位等上面。比如:

print(round(1627731, -1))
print(round(1627731, -2))
print(round(1627731, -3))

1627730
1627700
1628000

讨论

不要将舍入和格式化输出搞混淆了。 如果只是简单的输出一定宽度的数,则不需要使用 round() 函数。 只需要使用format()函数进行格式化并指定精度。比如:

x = 3.1415926
print(format(x, '0.2f'))
print(format(x, '0.3f'))
print('value is {:0.4f}'.format(x))

3.14
3.142
value is 3.1416

同样,不要试着去舍入浮点值来“修正”表面上看起来正确的问题。比如,你可能倾向于这样做:

a = 2.1
b = 4.2
c = a + b

print(c)
6.300000000000001

print(round(c, 2))
6.3

尽管浮点数在计算的时候会有一点点小的误差,但是这些小的误差是能被理解与容忍的。 如果不能允许这样的小误差(比如涉及到金融领域),那么就得考虑使用 decimal 模块了。

相关文章

网友评论

      本文标题:Python3 - 数字的四舍五入

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