Python round() 函式



Python round() 函式用於將給定的浮點數四捨五入到最接近的整數。四捨五入操作可以指定小數位數。如果沒有指定小數位數,則將四捨五入到最接近的整數,即 0 位小數。

例如,如果您想四捨五入一個數字,例如 6.5。它將四捨五入到最接近的整數 7。但是,數字 6.86 將四捨五入到一位小數,得到 6.9

語法

以下是 Python round() 函式的語法:

round(x[,n])

引數

  • x − 要四捨五入的數字。

  • n (可選) − 將給定數字四捨五入到的位數。其預設值為 0。

返回值

此函式返回從十進位制點四捨五入到指定位數的數字。

示例

以下示例演示了 Python round() 函式的用法。此處,要四捨五入的數字和小數位數作為引數傳遞給 round() 函式。

print ("round(80.23456, 2) : ", round(80.23456, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))

執行上述程式後,將產生以下結果:

round(80.23456, 2) :  80.23
round(100.000056, 3) :  100.0

示例

此處,沒有指定將給定數字四捨五入到的位數。因此,將使用其預設值 0。

# Creating the number
num = 98.65787
res = round(num)
# printing the result
print ("The rounded number is:",res)

執行上述程式碼後,我們將得到以下輸出:

The rounded number is: 99

示例

如果我們將負數作為引數傳遞,則此函式將返回最接近的負數。

在此示例中,建立了一個值為 '-783.8934771743767623' 的物件 'num'。將給定值四捨五入到的位數為 '6'。然後使用 round() 函式檢索結果。

# Creating the number
num = -783.8934771743767623
decimalPoints = 6
res = round(num, decimalPoints)
# printing the result
print ("The rounded number is:",res)

以下是上述程式碼的輸出:

The rounded number is: -783.893477

示例

在下面給出的示例中,建立了一個數組。為了在 Python 中四捨五入陣列,我們使用了 numpy 模組。然後將此陣列作為引數傳遞給 round() 函式,指定要四捨五入的位數為 4 位小數。

import numpy as np
# the arrray
array = [7.43458934, -8.2347985, 0.35658789, -4.557778, 6.86712, -9.213698]
res = np.round(array, 4)
print('The rounded array is:', res)

上述程式碼的輸出如下:

The rounded array is: [ 7.4346 -8.2348  0.3566 -4.5578  6.8671 -9.2137]
python_built_in_functions.htm
廣告