Math.trunc()
Math.trunc() 靜態方法透過移除所有小數部分來返回數字的整數部分。
試一試
console.log(Math.trunc(13.37));
// Expected output: 13
console.log(Math.trunc(42.84));
// Expected output: 42
console.log(Math.trunc(0.123));
// Expected output: 0
console.log(Math.trunc(-0.123));
// Expected output: -0
語法
js
Math.trunc(x)
引數
x-
一個數字。
返回值
x 的整數部分。
描述
Math.trunc() 的工作方式比其他三個 Math 方法:Math.floor()、Math.ceil() 和 Math.round() 更直接;它會截斷(去除)小數點以及它右邊的所有數字,無論引數是正數還是負數。
由於 trunc() 是 Math 的靜態方法,因此您總是將其用作 Math.trunc(),而不是用作您建立的 Math 物件的成員方法(Math 不是建構函式)。
示例
使用 Math.trunc()
js
Math.trunc(-Infinity); // -Infinity
Math.trunc("-1.123"); // -1
Math.trunc(-0.123); // -0
Math.trunc(-0); // -0
Math.trunc(0); // 0
Math.trunc(0.123); // 0
Math.trunc(13.37); // 13
Math.trunc(42.84); // 42
Math.trunc(Infinity); // Infinity
使用按位無操作來截斷數字
警告:由於存在不可忽略的邊緣情況,這不是 Math.trunc() 的 polyfill。
按位操作會將運算元轉換為 32 位整數,過去人們一直利用這一點來截斷浮點數。常見的方法包括:
js
const original = 3.14;
const truncated1 = ~~original; // Double negation
const truncated2 = original & -1; // Bitwise AND with -1
const truncated3 = original | 0; // Bitwise OR with 0
const truncated4 = original ^ 0; // Bitwise XOR with 0
const truncated5 = original >> 0; // Bitwise shifting by 0
請注意,這本質上是 toInt32,與 Math.trunc 不同。當值不滿足 -231 - 1 < value < 231 (-2147483649 < value < 2147483648) 時,轉換會溢位。
js
const a = ~~2147483648; // -2147483648
const b = ~~-2147483649; // 2147483647
const c = ~~4294967296; // 0
僅當您確信輸入值的範圍在 32 位整數範圍內時,才將 ~~ 用作 Math.trunc() 的替代方法。
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-math.trunc |
瀏覽器相容性
載入中…