[JS] JavaScript 數值與算數(Number and Math)
2 ** 3; // 2 的 3 次方(exponential)
num += 1; // 遞增
num -= 1; // 遞減
常用
產生隨機號碼
keywords: generate
, random number
, snippet
snippets: random
Math.random()
會產生 0(包含)到 1(不包含)的數值。
// 包含 min 和 max 的整數
function getRandomIntInclusive(min, max) {
// min = Math.ceil(min);
// max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; // The maximum is inclusive and the minimum is inclusive
}
- Math.random() @ MDN
- Generating Random Whole Numbers in JavaScript in a Specific Range @ StackOverflow
- Generate 4 digit random number using substring @ StackOverflow
無條件捨去到整數
// 使用 Math.floor()
Math.floor(30.78); // 30
// 使用 ~~
~~30.78; // 30
無條件進位
// 使用 Math.ceil
Math.ceil(30.78); // 31
四捨五入
// 四捨五入到整數位
Math.round(30.78); // 31
// 四捨五入
(3.12345).toFixed(0); // 四捨五入到整數
(3.12345).toFixed(2); // 四捨五入到小數第二位
檢驗是否為數值
keywords: Number.isNaN()
, isNaN()
, Number.isFinite()
const validateNumber = (n) => !Number.isNaN(parseFloat(n)) && Number.isFinite(n) && Number(n) === n;
validateNumber(0); // true
validateNumber('0'); // false
29.1 Use
Number.isNaN
instead of globalisNaN
@ airbnb validate number @ 30 seconds of code
次方(Power )
Math.pow(2, 4); // 2^4 = 16
2 ** 4; // 2^4 = 16
常數
Number.EPSILON
Number.EPSILON; // JavaScript 中最小的精度單位
在 JavaScript 中,如果兩個浮點數的差距小於 Number.EPSILON
則可以視為是相同的:
// 由於 a 和 b 的差距小於 Number.EPSILON,所以 a 和 b 在 JavaScript 中是可以視為相同的
const a = 0.1 + 0.2;
const b = 0.3;
Math.abs(a - b); // 5.551115123125783e-17
Math.abs(a - b) < Number.EPSILON; // true
其他參數
// 如果超過這個數值,就會失去精度
Number.MAX_SAFE_INTEGER; // 9007199254740991
Number.MIN_SAFE_INTEGER; // -9007199254740991