import math print(math.floor(3.14)) # 3 print(math.floor(-2.5)) # -3 (向負無窮方向) print(math.floor(5)) # 5
3.0)# Py3 直接得 int type(math.floor(3.14)) ## Py2 需轉換 int(math.floor(3.14)) # 3
| 值 | int(x) | math.floor(x) | math.ceil(x) | round(x) |
|---|---|---|---|---|
| 3.7 | 3 | 3 | 4 | 4 |
| 3.2 | 3 | 3 | 4 | 3 |
| -3.2 | -3 | -4 | -3 | -3 |
| -3.7 | -3 | -4 | -3 | -4 |
關鍵差異:int() 向零截斷,floor() 向負無窮,負數時結果不同。
pages = math.floor((total + size - 1) / size) 等價 (total + size - 1) // sizecol = math.floor(x / cell_width)bucket = math.floor(timestamp / interval) * intervalfrom decimal import Decimal, ROUND_FLOOR
d = Decimal('3.14159')
print(d.to_integral_value(rounding=ROUND_FLOOR)) # 3