国际访客建议访问 Primers 编程伙伴 国际版站点 > Python 教程 > round 以获得更好的体验。

# Python 的内置函数 round

请查看 Python 内建函数列表 了解更多相关 API。

说明:求近似值。

# 函数说明

def round(number, ndigits=None):
    '''
    求近似值

    :param number: 要计算的值
    :param ndigits: 保留的位数
    :return: 近似值
    '''

!subtitle:说明

求近似值,保留的位向最近的偶数舍入。

对于支持 round 的内置类型,结果会舍入至最接近的 10 的负 ndigits 次幂的倍数;如果与两个倍数同样接近,则优先选用偶数倍。

  • ndigits 为 0 或 None 时,保留整数;10 的负 ndigits 次幂即 10 的 0 次幂,也就是 1;优先选用 1 的偶数倍,也就是优先选用偶数本身。

  • ndigits 为负数时,相应的整数位优先取偶数。

  • ndigits 为正数时,相应的小数位优先取偶数;但由于浮点数精度误差的影响,结果可能不符合预期。

高精度需求的场景建议使用 decimal 模块。

!subtitle:参数

  • number - 要求近似值的值

  • ndigits - 结果要保留的小数位数,可用为负值,表示保留到整数位,默认为 None,表示保留整数

!subtitle:返回值

近似值。

# 示例

运行示例

print(round(3.1415926))         # 保留整数
print(round(3.1415926, 2))      # 保留两位小数

print(round(2.71828))           # 保留整数
print(round(2.71828, 2))        # 保留两位小数

print(round(2233.71828, -2))    # 保留到百位

print(round(2.5))               # 输出:2(优先选用偶数)
print(round(3.5))               # 输出:4(优先选用偶数)

print(round(25, -1))            # 输出:20(十位优先选用偶数)
print(round(35, -1))            # 输出:40(十位优先选用偶数)

print(round(0.25, 1))           # 输出:0.2(优先选用 0.1 的偶数倍)
print(round(0.35, 1))           # 输出:0.3(浮点数精度误差)

# 推荐阅读

本文 更新于: 2025-11-27 09:37:59 创建于: 2025-11-27 09:37:59