round(number[, ndigits]) 將數值四捨五入到指定小數位數。Python 3 採用「銀行家演算法」(Round half to even),即 .5 進位到最近的偶數,這與傳統「四捨五入」不同。本文詳細說明語法、行為、精度陷阱、Decimal 精確替代與實務建議。
round(number, ndigits=None)
# ndigits 省略或 None -> 回傳 int(最接近的整數)
# ndigits >= 0 -> 回傳 float,保留 ndigits 位小數
# ndigits < 0 -> 以 10 的冪次為單位捨入(十位、百位...)
print(round(80.23456, 2)) # 80.23
print(round(100.000056, 3)) # 100.0
print(round(-100.000056, 3)) # -100.0
print(round(1.5)) # 2
print(round(2.5)) # 2 ← 銀行家演算法:進到偶數
print(round(3.5)) # 4
print(round(1234, -2)) # 1200 (百位捨入)
# 看似 2.675 應進位到 2.68,實際輸出 2.67
print(round(2.675, 2)) # 2.67
# 原因:2.675 無法用二進位精確表示,實際儲存值略小
print(format(2.675, '.20f')) # 2.67499999999999982236
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
# 传统四捨五入 (ROUND_HALF_UP)
d = Decimal('2.675')
print(d.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)) # 2.68
# 银行家演算法 (ROUND_HALF_EVEN) - 与 round() 一致
print(d.quantize(Decimal('0.01'), rounding=ROUND_HALF_EVEN)) # 2.68 (Decimal 精確表示)
# 金融常用:固定兩位小數,四捨五入
def money_round(value):
return Decimal(str(value)).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
| 需求 | 建議做法 |
|---|---|
| 一般顯示用途 | round(x, 2) 或 f"{x:.2f}" |
| 金融/會計金額 | 務必用 Decimal,指定 ROUND_HALF_UP |
| 統計/科學計算 | round (銀行家) 可接受,或用 NumPy np.round |
| 避免浮點誤差顯示 | 格式化字串 format(x, '.2f') 自動處理 |
| ndigits 為負數 | 捨入到十位、百位等,如 round(1234, -1) == 1230 |
round 採傳統四捨五入(.5 總是進位),回傳 float。ndigits 省略時回傳 int。round 為 C 實作,極快。Decimal 較慢(約 10-100 倍),僅用於精度關鍵路徑。numpy.round 或 np.ndarray.round。理解 round() 的銀行家演算法與浮點數表示限制,並在金融場景堅持使用 Decimal,是寫出正確數值代碼的關鍵。