What is Math.trunc() in JavaScript?

Math is a built-in object in JavaScript that contains different methods and properties used to perform mathematical operations. It contains the trunc() function, which is used to extract the integer part of a specified number.

Trunc() function

Syntax

Math.trunc(param);

Parameter

  • param: This is the input value of the Number type, for which we want to find the trunc().

Number in JavaScript is a 64-bit double-precision value that is the same as a double in C# or Java.

Return value

  • Number: It returns the integer part of the input parameter param by removing the fractional part. It is of the Number type.

  • NaN: The function returns this if the input parameter param is anything other than a Number.

trunc() is different from floor(), ceil() and round() as it simply cuts off the decimal point and fractional part, instead of doing any rounding.

Code

console.log("trunc(-1.342) = " + Math.trunc(-1.342));
console.log("trunc(1.342) = " + Math.trunc(1.342));
console.log("trunc(0.041) = " + Math.trunc(0.041));
console.log("trunc('1.542') = " + Math.trunc('1.542'));
console.log("trunc(NaN) = " + Math.trunc(NaN));
console.log("trunc() = " + Math.trunc());
console.log("trunc('educative') = " + Math.trunc('educative'));

Free Resources