JavaScript Math trunc() is a “static method that returns the integer part of a number by removing any fractional digits”. The Math.trunc() method removes the decimals, but it does NOT round the number.
Syntax
Math.trunc(number)
Parameter(s)
number: It is the floating-point number whose integral part is to be returned.
Return Value
The integral part of x by removing the part after the decimal point.
Example 1: How to Use Math.trunc() Method
let a = 12.25;
let b = -6.3;
let c = 0.35;
let d = -0.2;
let e = [4.3]; // array with single element
console.log(Math.trunc(a));
console.log(Math.trunc(b));
console.log(Math.trunc(c));
console.log(Math.trunc(d));
console.log(Math.trunc(e));
Output
12
-6
0
-0
4
Example 2: Math.trunc() with Non-numeric function
The following example shows the cases where NaN is returned.
let a = "Hello, world"; // non-numeric string
let b; // empty variable
let c = [1, 2, 3, 4]; // array with more than one elements
let d = {}; // empty object
console.log(Math.trunc(a));
console.log(Math.trunc(b));
console.log(Math.trunc(c));
console.log(Math.trunc(d));
Output
NaN
NaN
NaN
NaN
Example 3: Math.trunc() with null and empty values
The following example demonstrates the cases where zero is returned.
let a = null;
let b = ""; // empty string
let c = []; // empty array
console.log(Math.trunc(a));
console.log(Math.trunc(b));
console.log(Math.trunc(c));
Output
0
0
0
Example 4: Math.trunc() with Numeric String
let string = "21.1993";
// trunc() with string argument
let value = Math.trunc(string);
console.log(value);
Output
21
Browser compatibility
- Google Chrome 38 and above
- Firefox 25 and above
- Opera 25 and above
- Safari 8 and above
- Edge 12 and above
That’s it.