Python 的 round() 函数用于对浮点数进行四舍五入操作,其核心语法和行为如下:
基础用法
round(number, ndigits=None)
-
number:需舍入的数字(支持整数/浮点数) -
ndigits:保留的小数位数(默认为None,舍入到整数)
核心规则
-
标准四舍五入
round(3.14159) 3(默认舍入到整数) round(2.675, 2) 2.67(注意:实际可能因浮点精度显示2.67) -
保留指定位数
round(1.23456, 3) 1.235(保留3位小数) round(123.456, -1) 120.0(负值表示整数位舍入) -
银行家舍入法(Round Half to Even)
当恰为中间值(如 0.5)时,舍入到最近的偶数:round(0.5) 0(偶数) round(1.5) 2(偶数) round(2.5) 2(偶数)
浮点精度注意
因 IEEE 754 浮点数限制,某些值舍入结果可能非预期:
round(2.675, 2) 预期 2.68,实际输出 2.67
👉 解决方案:对精度敏感场景使用 decimal 模块:
from decimal import Decimal, ROUND_HALF_UP
float(Decimal('2.675').quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)) 2.68
实用示例
金额格式化
price = 19.987
print(f"¥{round(price, 2)}") ¥19.99
科学计算截断
gravity = 9.80665
print(round(gravity, 1)) 9.8
整数位舍入
population = 123456
print(round(population, -3)) 123000
💡 最佳实践:金融计算避免使用
round(),优先选择decimal模块确保精度。