#Python 的内置函数 round
说明:求近似值。
#函数说明
def round(number, ndigits=None):
'''
求近似值
:param number: 要计算的值
:param ndigits: 保留的位数
:return: 近似值
'''
说明
求近似值,保留的位向最近的偶数舍入。
对于支持 round
的内置类型,结果会舍入至最接近的 10 的负 ndigits
次幂的倍数;如果与两个倍数同样接近,则优先选用偶数倍。
ndigits
为 0 或None
时,保留整数;10 的负ndigits
次幂即 10 的 0 次幂,也就是 1;优先选用 1 的偶数倍,也就是优先选用偶数本身。ndigits
为负数时,相应的整数位优先取偶数。ndigits
为正数时,相应的小数位优先取偶数;但由于浮点数精度误差的影响,结果可能不符合预期。
高精度需求的场景建议使用 decimal
模块。
参数
number
- 要求近似值的值ndigits
- 结果要保留的小数位数,可用为负值,表示保留到整数位,默认为None
,表示保留整数
返回值
近似值。
#示例
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(浮点数精度误差)