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 參數能夠是負數,這種狀況下, 舍入運算會做用在十位、百位、千位等上面
複製代碼

特別的git

# 特別的
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
相關文章
相關標籤/搜索