JavaScript Math.trunc() Method



The JavaScript Math.trunc() method accepts a numeric value as an argument and returns the integer part of the number by truncating the decimal digits. If the argument is NaN or Infinity, the result is NaN or Infinity, respectively. If the argument is 0 or -0, the result will be 0.

Here's a basic explanation of how Math.trunc() works −

  • For positive numbers, Math.trunc() simply removes the decimal part, leaving only the integer part as it is.
  • For negative numbers, Math.trunc() removes the decimal part as well but the sign of the number will remain same.

Note: This method does not round the number instead, it truncates the decimals digits.

Syntax

Following is the syntax of JavaScript Math.trunc() method −

Math.trunc(x)

Parameters

This method accepts only one parameter. The same is described below −

  • x: A numeric value.

Return value

This method returns a "number" that represents the integer part of the provided number.

Example 1

In the following example, we are demonstrating the basic usage of JavaScript Math.trunc() method −

<html>
<body>
<script>
   const result = Math.trunc(3.75);
   document.write(result);
</script>
</body>
</html>

Output

If we execute the above program, it returns "3" as result by truncating the decimal part.

Example 2

For negative numbers, the Math.trunc() method also truncates the decimal part and retains the sign −

<html>
<body>
<script>
   const result = Math.trunc(-9.123);
   document.write(result);
</script>
</body>
</html>

Output

As we can in the output, the decimals are truncated and sign has been retained the same.

Example 3

If the argument is provided as a string, this method will convert it to a number and then truncates the decimal part −

<html>
<body>
<script>
   const result = Math.trunc("42.9876");
   document.write(result);
</script>
</body>
</html>

Output

If we execute the above program, it will return 42 as result.

Example 4

If the provided number does not have any decimals, this method will return the number without any modifications −

<html>
<body>
<script>
   const result = Math.trunc(42);
   document.write(result);
</script>
</body>
</html>

Output

As we can see the output, 42 has been returned.

Example 5

If the provided argument is 0 or -0, this method will return 0 as result −

<html>
<body>
<script>
   const result1 = Math.trunc(0);
   const result2 = Math.trunc(-0);
   document.write(result1, <br>, result2);
</script>
</body>
</html>

Output

As we can see the output, 0 is returned as a result.

Example 6

If the provided argument is NaN or Infinity, this method will return NaN or Infinity, respectively −

<html>
<body>
<script>
   const result1 = Math.trunc(NaN);
   const result2 = Math.trunc(Infinity);
   document.write(result1, <br>, result2);
</script>
</body>
</html>

Output

As we can see the output, Math.trunc() returned NaN and Infinity as result.

Advertisements