python中保留小數位的方法


python保留小數位的方法

  • format函數
print('{:.3f}  {:.2f}'.format(1.23456,0.1256))#1.235  0.13
:.3f :3f表示保留3位有效數字
print(format(1.2345,'.2f'))#1.23
.2f :表示小數點后保留兩位有效數字

使用了占位符{}可以同時輸出多個,后者一次只能輸出一個,需要注意的是占位符中的冒號不能丟
  • ’%.xf‘ 方法
print('%.2f'%1.2356)#1.24
  • 通過round()函數
print(round(1.2345,3))#1.234
print(round(2.3568,2))#2.36
#大於等於六時進位
print(round(2.9))#3
print(round(2.6))#3
print(round(2.5))#2
print(round(2.1))#2


免責聲明!

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



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