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 |
浏览器兼容性
加载中…