Math.trunc()

Math.trunc() 静态方法通过删除任何小数位来返回数字的整数部分。

¥The Math.trunc() static method returns the integer part of a number by removing any fractional digits.

Try it

语法

¥Syntax

js
Math.trunc(x)

参数

¥Parameters

x

一个号码。

返回值

¥Return value

x 的整数部分。

¥The integer part of x.

描述

¥Description

与其他三种 Math 方法不同:Math.floor()Math.ceil()Math.round()Math.trunc() 的工作方式非常简单。无论参数是正数还是负数,它都会截断(切断)点及其右侧的数字。

¥Unlike the other three Math methods: Math.floor(), Math.ceil() and Math.round(), the way Math.trunc() works is very simple. It truncates (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number.

因为 trunc()Math 的静态方法,所以你始终将其用作 Math.trunc(),而不是用作你创建的 Math 对象的方法(Math 不是构造函数)。

¥Because trunc() is a static method of Math, you always use it as Math.trunc(), rather than as a method of a Math object you created (Math is not a constructor).

示例

¥Examples

使用 Math.trunc()

¥Using 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

使用按位无操作来截断数字

¥Using bitwise no-ops to truncate numbers

警告:由于不可忽略的边缘情况,这不是 Math.trunc() 的 Polyfill。

¥Warning: This is not a polyfill for Math.trunc() because of non-negligible edge cases.

位运算将其操作数转换为 32 位整数,历史上人们利用它来截断浮点数。常见技术包括:

¥Bitwise operations convert their operands to 32-bit integers, which people have historically taken advantage of to truncate float-point numbers. Common techniques include:

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),转换会溢出。

¥Beware that this is essentially toInt32, which is not the same as Math.trunc. When the value does not satisfy -231 - 1 < value < 231 (-2147483649 < value < 2147483648), the conversion would overflow.

js
const a = ~~2147483648; // -2147483648
const b = ~~-2147483649; // 2147483647
const c = ~~4294967296; // 0

仅当你确信输入范围在 32 位整数范围内时,才使用 ~~ 代替 Math.trunc()

¥Only use ~~ as a substitution for Math.trunc() when you are confident that the range of input falls within the range of 32-bit integers.

规范

Specification
ECMAScript Language Specification
# sec-math.trunc

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看