totn JavaScript

JavaScript: Math trunc() function

This JavaScript tutorial explains how to use the math function called trunc() with syntax and examples.

Description

In JavaScript, trunc() is a function that is used to return the integer portion of a number. It truncates the number and removes all fractional digits. Because the trunc() function is a static function of the Math object, it must be invoked through the placeholder object called Math.

Syntax

In JavaScript, the syntax for the trunc() function is:

Math.trunc(number);

Parameters or Arguments

number
The number to truncate.

Returns

The trunc() function returns only the integer portion of a number.

Note

  • Math is a placeholder object that contains mathematical functions and constants of which trunc() is one of these functions.

Example

Let's take a look at an example of how to use the trunc() function in JavaScript.

For example:

console.log(Math.trunc(32.65));
console.log(Math.trunc(8.1));
console.log(Math.trunc(-4.2));

In this example, we have invoked the trunc() function using the Math class.

We have written the output of the trunc() function to the web browser console log, for demonstration purposes, to show what the trunc() function returns.

The following will be output to the web browser console log:

32
8
-4

In this example, the first output to the console log returned 32 which is 32.65 truncated to an integer value.

The second output to the console log returned 8 which is 8.1 truncated to an integer value.

The third output to the console log returned -4 which is -4.2 truncated to an integer value.