The Math trunc() method is used to remove the fractional part of a number, leaving only the integer part.
Syntax
Math.trunc(number)
Parameters
number(required): The floating-point number whose integral part is to be removed.
Return Value
Returns the integer part of the given number.
If you pass a non-numeric value, it returns NaN.
Visual Representation
Example 1: How to Use Math trunc() Method
let a = 12.25; //positive float number
let b = -12.35; //negative float number
let c = 0.55; //positive number between 0 and 1
let d = -0.55; //negative number between 0 and 1
console.log(Math.trunc(a));
console.log(Math.trunc(b));
console.log(Math.trunc(c));
console.log(Math.trunc(d));
Output
12
-12
0
0
Example 2: Handling Non-numeric Value
let a = "Hello, world"; // non-numeric string
let b = [1, 2, 3, 4]; // array with more than one elements
let c = {}; // empty object
console.log(Math.trunc(a));
console.log(Math.trunc(b));
console.log(Math.trunc(c));
Output
NaN
NaN
NaN
Example 3: Handling null and empty values
let a = null;
let b; // empty value
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: Passing Numeric String
console.log(Math.trunc("12.35"));
Output
12
Browser compatibility
- Google Chrome 38 and above
- Firefox 25 and above
- Opera 25 and above
- Safari 8 and above
- Edge 12 and above
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.