Python之数字的四舍五入(round(value, ndigits) 函数)

round(value, ndigits) 函数
print(round(1.23))  # 1
print(round(1.27))  # 1

print(round(1.23,1))  # 1.2  第二个参数保留的小数位数
print(round(1.27,1))  # 1.3
print(round(10.273,-1))  # 10.0
print(round(10273,-1))  # 10270
# 传给 round() 函数的 ndigits 参数可以是负数,这种情况下, 舍入运算会作用在十位、百位、千位等上面

特别的

# 特别的
print(round(1.5))  # 2
print(round(2.5))  # 2
print(round(3.5))  # 4
# 当一个值刚好在两个边界的中间的时候, round 函数返回离它最近的偶数。 也就是说,对1.5或者2.5的舍入运算都会得到2。
不要将舍入和格式化输出搞混淆了。 如果你的目的只是简单的输出一定宽度的数,你不需要使用 round() 函数。 而仅仅只需要在格式化的时候指定精度即可
x=1.23456
print(format(x,"0.1f"))  # 1.2
print(format(x,"0.2f"))  # 1.23
print(format(x,"0.3f"))  # 1.235

print("格式化精度{:0.4f}".format(x))  # 格式化精度1.2346
原文地址:https://www.cnblogs.com/zzy-9318/p/10461928.html