萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

Python math.floor() 向下取整:捨棄小數部分的正確姿勢

基本用法

import math

print(math.floor(3.14))   # 3
print(math.floor(-2.5))   # -3  (向負無窮方向)
print(math.floor(5))      # 5

返回類型

  • Python 3:返回 int
  • Python 2:返回 float (如 3.0)
# Py3 直接得 int
type(math.floor(3.14))  # 

# Py2 需轉換
int(math.floor(3.14))   # 3

對比:int() 截斷 vs floor() 向下取整

值int(x)math.floor(x)math.ceil(x)round(x)
3.73344
3.23343
-3.2-3-4-3-3
-3.7-3-4-3-4

關鍵差異:int() 向零截斷,floor() 向負無窮,負數時結果不同。

常見場景

  • 分頁計算:pages = math.floor((total + size - 1) / size) 等價 (total + size - 1) // size
  • 網格坐標:col = math.floor(x / cell_width)
  • 時間對齊:bucket = math.floor(timestamp / interval) * interval

Decimal 高精度場景

from decimal import Decimal, ROUND_FLOOR
d = Decimal('3.14159')
print(d.to_integral_value(rounding=ROUND_FLOOR))  # 3
copyright © 萬盛學電腦網 all rights reserved