當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python round()用法及代碼示例

在本教程中,我們將借助示例了解 Python round() 函數。

round() 函數返回一個四舍五入到指定小數位數的浮點數。

示例

number = 13.46

# round the number
rounded_number = round(number)
print(rounded_number)

# Output: 13

round() 語法

用法:

round(number, ndigits)

參數:

round() 函數有兩個參數:

  • number- 要四舍五入的數字
  • ndigits(可選)- 給定數字四舍五入的數字;默認為 0

返回:

round() 函數返回

  • 如果未提供ndigits,則與給定數字最接近的整數
  • 如果提供了ndigits,則數字四舍五入到ndigits 數字

示例 1:round() 如何在 Python 中工作?

# for integers
print(round(10))

# for floating point
print(round(10.7))

# even choice
print(round(5.5))

輸出

10
11
6

示例 2:將數字四舍五入到給定的小數位數

print(round(2.665, 2))
print(round(2.675, 2))

輸出

2.67
2.67

注意: 的行為round()對於浮點數可能會令人驚訝。注意round(2.675, 2)2.67而不是預期的2.68.這不是錯誤:這是因為大多數小數部分不能完全表示為浮點數。

當十進製 2.675 轉換為二進製浮點數時,它再次被二進製近似值替換,其精確值為:

2.67499999999999982236431605997495353221893310546875

因此,它向下舍入為 2.67。

如果您處於需要這種精度的情況,請考慮使用 decimal 模塊,該模塊專為浮點運算而設計:

from decimal import Decimal

# normal float
num = 2.675
print(round(num, 2))

# using decimal.Decimal (passed float as string for precision)
num = Decimal('2.675')
print(round(num, 2))

輸出

2.67
2.68

相關用法


注:本文由純淨天空篩選整理自 Python round()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。