代码点读机 / Python / round

round Python · 内置函数

`round` 对数字进行四舍五入,可以指定保留几位小数。这个没啥好比喻的,只能单独记。

怎么用

round(数字)               # 四舍五入到整数
round(数字, 小数位数)      # 四舍五入到指定小数位

小例子

print(round(3.14159))
print(round(3.14159, 2))
print(round(2.5))

运行结果

3
3.14
2

对比:注意 Python 的舍入规则

# Python 使用银行家舍入法:四舍六入五取偶
print(round(0.5))   # 0
print(round(1.5))   # 2
print(round(2.5))   # 2
print(round(3.5))   # 4
这是因为浮点数表示不精确,以及 round 对 .5 的处理是向偶数靠拢。

常见使用场景

1. 保留两位小数显示金额:
价格 = 9.999
print(round(价格, 2))   # 10.0
2. 对计算结果取整:
平均值 = sum([85, 90, 78]) / 3
print(round(平均值))   # 84
3. 控制输出精度。

提醒:- `round` 不是严格数学上的四舍五入,而是银行家舍入法(五可能舍去也可能进位)。 - 如果省略第二个参数,默认保留 0 位小数,返回整数。 - 浮点数运算可能有精度问题,`round(2.675, 2)` 可能得到 `2.67` 而不是 `2.68`,这是浮点表示误差造成的。

官方文档:https://docs.python.org/zh-cn/3/library/functions.html#round

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条