Python数字处理技巧(1):精度舍入、精确运算与格式化、进制数、大数打包与解包、复数、NaN与分数处理
发布时间
阅读量:
阅读量
1. 数字的四舍五入
当我们需要对整数 或者 浮点数进行四舍五入的时候。
- round(value, ndigits) /// 内置函数
对浮点数进行四舍五入(传入的ndigit应该是正值,作用于十分位、百分位...):
print( round(1.23, 1) ) # 1.2
print( round(1.27, 1) ) # 1.3
print( round(-1.27, 1) ) #-1.3
print( round(1.25361, 3)) #1.254
print( round(2.5, 0) ) #2.0 近似到最近的偶数
对整数进行四舍五入(传入的ndigit应该是自然数,作用于个位、十位、百位...)
print( round(314159, -1)) #314160
print( round(314159, -2)) #314200
print( round(314159, -3)) #314000
Comment:
请避免将舍入round与格式化format混淆用于输出结果。 如果我们的目标仅仅是将一定宽度的数值显示出来而不必使用round
全部评论 (0)
还没有任何评论哟~
