萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Math 對象方法完全指南:取整、四捨五入、隨機數與數學運算

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)

Math 對象完整方法速查表

方法描述範例
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;
}

保留 N 位小數

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,建議重點記憶。

copyright © 萬盛學電腦網 all rights reserved