Math.floor()
Math.floor() 靜態方法始終向下取整,並返回小於或等於給定數字的最大整數。
試一試
console.log(Math.floor(5.95));
// Expected output: 5
console.log(Math.floor(5.05));
// Expected output: 5
console.log(Math.floor(5));
// Expected output: 5
console.log(Math.floor(-5.05));
// Expected output: -6
語法
js
Math.floor(x)
引數
x-
一個數字。
返回值
小於或等於 x 的最大整數。它的值與 -Math.ceil(-x) 相同。
描述
因為 floor() 是 Math 的靜態方法,所以你總是使用 Math.floor() 的形式來呼叫它,而不是用你建立的 Math 物件的方法來呼叫(Math 不是一個建構函式)。
示例
使用 Math.floor()
js
Math.floor(-Infinity); // -Infinity
Math.floor(-45.95); // -46
Math.floor(-45.05); // -46
Math.floor(-0); // -0
Math.floor(0); // 0
Math.floor(4); // 4
Math.floor(45.05); // 45
Math.floor(45.95); // 45
Math.floor(Infinity); // Infinity
小數調整
在此示例中,我們實現了一個名為 decimalAdjust() 的方法,該方法是對 Math.floor()、Math.ceil() 和 Math.round() 的增強方法。前三個 Math 函式總是將輸入調整到個位數,而 decimalAdjust 接受一個 exp 引數,該引數指定數字應調整到的小數點左側的位數。例如,-1 表示它將小數點後保留一位(如“× 10-1”)。此外,它還允許你透過 type 引數選擇調整方式——round、floor 或 ceil。
它的實現方式是先將數字乘以 10 的冪,然後將結果四捨五入到最接近的整數,最後再除以該冪。為了更好地保持精度,它利用了 Number 的 toString() 方法,該方法以科學計數法(如 6.02e23)表示大數字或小數字。
js
/**
* Adjusts a number to the specified digit.
*
* @param {"round" | "floor" | "ceil"} type The type of adjustment.
* @param {number} value The number.
* @param {number} exp The exponent (the 10 logarithm of the adjustment base).
* @returns {number} The adjusted value.
*/
function decimalAdjust(type, value, exp) {
type = String(type);
if (!["round", "floor", "ceil"].includes(type)) {
throw new TypeError(
"The type of decimal adjustment must be one of 'round', 'floor', or 'ceil'.",
);
}
exp = Number(exp);
value = Number(value);
if (exp % 1 !== 0 || Number.isNaN(value)) {
return NaN;
} else if (exp === 0) {
return Math[type](value);
}
const [magnitude, exponent = 0] = value.toString().split("e");
const adjustedValue = Math[type](`${magnitude}e${exponent - exp}`);
// Shift back
const [newMagnitude, newExponent = 0] = adjustedValue.toString().split("e");
return Number(`${newMagnitude}e${Number(newExponent) + exp}`);
}
// Decimal round
const round10 = (value, exp) => decimalAdjust("round", value, exp);
// Decimal floor
const floor10 = (value, exp) => decimalAdjust("floor", value, exp);
// Decimal ceil
const ceil10 = (value, exp) => decimalAdjust("ceil", value, exp);
// Round
round10(55.55, -1); // 55.6
round10(55.549, -1); // 55.5
round10(55, 1); // 60
round10(54.9, 1); // 50
round10(-55.55, -1); // -55.5
round10(-55.551, -1); // -55.6
round10(-55, 1); // -50
round10(-55.1, 1); // -60
// Floor
floor10(55.59, -1); // 55.5
floor10(59, 1); // 50
floor10(-55.51, -1); // -55.6
floor10(-51, 1); // -60
// Ceil
ceil10(55.51, -1); // 55.6
ceil10(51, 1); // 60
ceil10(-55.59, -1); // -55.5
ceil10(-59, 1); // -50
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-math.floor |
瀏覽器相容性
載入中…