JavaScript Math trunc() Method

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

Visual Representation of JavaScript Math trunc() Method

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 valuesVisual Representation of 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

  1. Google Chrome 38 and above
  2. Firefox 25 and above
  3. Opera 25 and above
  4. Safari 8 and above
  5. Edge 12 and above

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.