Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Math.trunc()

BaselineWidely available

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

Try it

console.log(Math.trunc(13.37));// Expected output: 13console.log(Math.trunc(42.84));// Expected output: 42console.log(Math.trunc(0.123));// Expected output: 0console.log(Math.trunc(-0.123));// Expected output: -0

Syntax

js
Math.trunc(x)

Parameters

x

A number.

Return value

The integer part ofx.

Description

The wayMath.trunc() works is more straightforward than the other threeMath methods:Math.floor(),Math.ceil() andMath.round(); ittruncates (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number.

Becausetrunc() is a static method ofMath, you always use it asMath.trunc(), rather than as a method of aMath object you created (Math is not a constructor).

Examples

Using Math.trunc()

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

Using bitwise no-ops to truncate numbers

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

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 negationconst truncated2 = original & -1; // Bitwise AND with -1const truncated3 = original | 0; // Bitwise OR with 0const truncated4 = original ^ 0; // Bitwise XOR with 0const truncated5 = original >> 0; // Bitwise shifting by 0

Beware that this is essentiallytoInt32, which is not the same asMath.trunc. When the value does not satisfy -231 - 1 <value < 231 (-2147483649 <value < 2147483648), the conversion would overflow.

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

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

Specifications

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

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp