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.
Syntax
Math.trunc(param);
Parameter
param: This is the input value of theNumbertype, for which we want to find thetrunc().
Numberin JavaScript is a 64-bit double-precision value that is the same as adoublein C# or Java.
Return value
-
Number: It returns the integer part of the input parameterparamby removing the fractional part. It is of theNumbertype. -
NaN: The function returns this if the input parameterparamis anything other than aNumber.
trunc()is different fromfloor(),ceil()andround()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'));