Skip to main content
☘️ Septvean's Documents
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

四舍五入

Python 最常用的四舍五入方法是内置的 round(number, ndigits) 函数。若要指定精度,传入保留位数即可(如 round(3.1415, 2) 得 3.14)。需注意,Python 默认采用“银行家舍入法”(四舍六入五成双,遇五时靠拢偶数)而非严格的数学四舍五入。

一、 内置函数 round()

最直接的舍入方式是使用 round() 函数。当第二个参数省略时,返回最接近的整数。

# 默认取整,遵循银行家舍入(结果为偶数)
print(round(2.5))  # 输出: 2
print(round(3.5))  # 输出: 4

# 指定小数位数
print(round(3.14159, 2))  # 输出: 3.14
print(round(2.675, 2))    # 输出: 2.67(受浮点数底层精度限制,可能出现意外结果)

二、 精确四舍五入:decimal 模块

由于计算机二进制无法精确表示所有浮点数(如 0.1),对于财务计算等需要绝对精确的场景,推荐使用内置的 decimal 模块。

from decimal import Decimal, ROUND_HALF_UP

# 必须将浮点数转为字符串格式以保证精度
num = Decimal('2.675')

# 使用 ROUND_HALF_UP 模式进行标准数学四舍五入
rounded_num = num.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
print(rounded_num)  # 输出: 2.68