Math.trunc()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Math.trunc() 方法会将数字的小数部分去掉,只保留整数部分。

语法

Math.trunc(value)

参数

value

任意数字

返回值

给定数字的整数部分

描述

不像 Math 的其他三个方法: Math.floor()Math.ceil()Math.round()Math.trunc() 的执行逻辑很简单,仅仅是删除掉数字的小数部分和小数点,不管参数是正数还是负数。

传入该方法的参数会被隐式转换成数字类型。

因为 trunc()Math 对象的静态方法,你必须用 Math.trunc() 来使用,而不是调用你创建的 Math 对象的一个实例方法(Math 没有构造函数)

示例

js
Math.trunc(13.37); // 13
Math.trunc(42.84); // 42
Math.trunc(0.123); //  0
Math.trunc(-0.123); // -0
Math.trunc("-1.123"); // -1
Math.trunc(NaN); // NaN
Math.trunc("foo"); // NaN
Math.trunc(); // NaN

规范

Specification
ECMAScript® 2025 Language Specification
# sec-math.trunc

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
trunc

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见