日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python保留小數函數的幾種使用總結_python

作者:梁嘵生 ? 更新時間: 2023-06-21 編程語言

python保留小數——‘%f’

‘%.nf’% x(定義的變量)

例子:

a = 82.16332
print('%.1f'% a)
print('%.2f'% a)
print('%.3f'% a)
print('%.4f'% a)
print('%.10f'% a)

輸出結果

python保留小數——format()函數

Python2.6 開始,新增了一種格式化字符串的函數 str.format(),它增強了字符串格式化的功能。

基本語法是通過 {} 和 : 來代替以前的 % 。

format 函數可以接受不限個參數,位置可以不按順序。

例子

print("{:.1f}".format(0.167123))
print("{:.2f}".format(0.167123))
print("{:.3f}".format(0.167123))
print("{:.4f}".format(0.167123))
print("{:.10f}".format(0.167123))

輸出結果

因為format()函數位置可以不按照順序,所以也可以這樣寫

print(format(0.167123, '.1f'))
print(format(0.167123, '.2f'))
print(format(0.167123, '.3f'))
print(format(0.167123, '.10f'))

輸出結果

通過觀察數據可以發現上面兩個數據都是進行‘四舍五入’的。

python保留小數——round()函數

round() 方法返回浮點數x的四舍五入值。

用法:round(數字,n),n為“數值表達式,表示從小數點位數”。

用例

s = 1.15457321
print("round(80.23456, 2) : ", round(80.23456, 2))
print( round(1203245, 3))
print(round(s,10))

輸出結果

而對于round()函數有時候會出現一些問題,有時候無法提供正確的輸出

例子

print(round(2.675,2))
print(round(8.875,2))

輸出結果

如果按照’四舍五入‘的話應該是輸出2.68的,但是結果是2.67,而8.875輸出的是‘四舍五入’的值8.88

對于python round()函數

python中的舍入函數將十進制值四舍五入為給定的位數,如果我們不提供n(即十進制后的位數),則會將數字四舍五入為最接近的整數。

例子

#int
print(round(12))
#float
print(round(66.6))
print(round(45.5))
print(round(92.4))

輸出結果

當提供第二個參數的時候,如果提供的參數n>=5的時候,則最后一個十進制數字將增加一,直至舍入后的值,不然的話將與提供的相同

例子

print(round(1.221, 2))
print(round(1.222, 2))
print(round(1.223, 2))
print(round(1.224, 2))
print(round(1.215, 2))
print(round(1.226, 2))
print(round(1.227, 2))
print(round(1.228, 2))
print(round(1.279, 2))

輸出結果

可以看出是有的進位成功,有的是進位不成功的,所以這個round()函數不太好用,而對整數的進位是正確的

所以不建議使用這個方法

python保留小數——math.floor

floor() 返回數字的下舍整數。

使用floor的方法,需要引入math模塊

floor()表示的是向下取舍

例子

import math
print("math.floor(-45.17) : ", math.floor(-45.17))
print("math.floor(100.12) : ", math.floor(100.12))
print("math.floor(100.72) : ", math.floor(100.72))
print("math.floor(119L) : ", math.floor(119))
print("math.floor(math.pi) : ", math.floor(math.pi))

輸出結果

進行小數操作可以這樣使用,先進行擴大數值的n次方,然后再除以n次方,即可得到’四舍五不入‘的數值

例子:(保留兩位小數)

import math
print(math.floor(1.25754*10**2)/10**2)

輸出結果

如果想要輸出三位小數不進行‘四舍五入’,可以先乘10**3然后除以10**3

python保留小數——不進行四舍五入,簡單粗暴法int()

例子

print(int(1.23456 * 1000) / 1000 )

輸出結果

放大指定的倍數,然后取整,然后再除以指定的倍數。

可以利用上面的函數進行保留2位小數、3位小數、4位小數等

原文鏈接:https://blog.csdn.net/qq_61897141/article/details/129192180

  • 上一篇:沒有了
  • 下一篇:沒有了

相關推薦

欄目分類
最近更新