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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM