Math 是 JavaScript 內建的靜態數學對象,提供豐富的數學常數與方法,無需實例化即可直接調用。本文系統整理 Math 對象的核心方法,重點講解四種取整方式的差異,並提供完整方法速查表。
以 5/2 = 2.5 為例:
| 方法 | 描述 | 代碼 | 結果 |
|---|---|---|---|
parseInt() | 丟棄小數部分,保留整數 | parseInt(5/2) | 2 |
Math.ceil() | 向上取整(有小數就進 1) | Math.ceil(5/2) | 3 |
Math.round() | 四捨五入 | Math.round(5/2) | 3 |
Math.floor() | 向下取整 | Math.floor(5/2) | 2 |
關鍵差異:
parseInt() 直接截斷,負數行為同 Math.ceil()(如 parseInt(-2.5) = -2)Math.floor() 永遠向下,負數會變更小(如 Math.floor(-2.5) = -3)Math.ceil() 永遠向上,負數會變更大(如 Math.ceil(-2.5) = -2)| 方法 | 描述 | 範例 |
|---|---|---|
abs(x) | 絕對值 | Math.abs(-5) // 5 |
acos(x) | 反余弦 | Math.acos(0.5) // 1.047... |
asin(x) | 反正弦 | Math.asin(0.5) // 0.523... |
atan(x) | 反正切 | Math.atan(1) // 0.785... |
atan2(y,x) | 從 X 軸到點 (x,y) 的角度 | Math.atan2(1,1) // 0.785... |
ceil(x) | 向上取整 | Math.ceil(2.1) // 3 |
cos(x) | 余弦 | Math.cos(0) // 1 |
exp(x) | e 的指數 | Math.exp(1) // 2.718... |
floor(x) | 向下取整 | Math.floor(2.9) // 2 |
log(x) | 自然對數 | Math.log(Math.E) // 1 |
max(x,y,...) | 最大值 | Math.max(1,5,3) // 5 |
min(x,y,...) | 最小值 | Math.min(1,5,3) // 1 |
pow(x,y) | x 的 y 次方 | Math.pow(2,3) // 8 |
random() | 0~1 隨機數 | Math.random() // 0.123... |
round(x) | 四捨五入 | Math.round(2.5) // 3 |
sin(x) | 正弦 | Math.sin(Math.PI/2) // 1 |
sqrt(x) | 平方根 | Math.sqrt(9) // 3 |
tan(x) | 正切 | Math.tan(0) // 0 |
// min 到 max 之間(含邊界)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function toFixed(num, digits) {
const factor = Math.pow(10, digits);
return Math.round(num * factor) / factor;
}
所有列出方法在主流瀏覽器(Chrome, Firefox, Safari, Edge, IE9+)均完整支援。toSource() 僅 Firefox 支援,生產環境不建議使用。
掌握 Math 對象的取整差異與常用方法,能讓數值處理更精準高效。實務中最常用的是 round、floor、ceil、random、max/min,建議重點記憶。