JavaScript Truncate

The JavaScript Truncate function (trunc(x)) is a Math function. The Truncate function is used to remove the decimal values from specified expression and return the integer value. The syntax of the JavaScript Truncate Function is:

Math.trunc(number);

Number: It can be a decimal or a numerical expression

  • If the number argument is a positive or negative number, JS truncate function will return the truncated value.
  • If it is not a number, the trunc function will return NaN.
  • And if it is Null, the trunc function will return Zero.

JavaScript Truncate Function Example

The JavaScript Truncate Function removes the decimal values and returns the integer value. In this Truncate example, We are going to find the truncated values of different data types using trunc() and display the output

  • First, we used the trunc Function on the Positive Decimal values.
  • Next two statements, We used the JavaScript trunc Function on the negative Decimal values.
  • Next, we tried trunc Function on the string value. It will return NaN (Not a Number) as output
  • Last, we tried JS truncate Math function on Null value and it returns Zero
<!DOCTYPE html>
<html>
<head>
    <title> JavaScript TRUNCATE Function </title>
</head>
<body>
  <h1> JavaScript TRUNC Function </h1>
  <p id = "Pos"></p>
  <p id = "Neg"></p>
  <p id = "Dec"></p>
  <p id = "Neg_Dec"></p>
  <p id = "Str"></p>
  <p id = "Null"></p>
  <script>
    document.getElementById("Pos").innerHTML = Math.trunc(10.95);
    document.getElementById("Dec").innerHTML = Math.trunc(10.05);
    document.getElementById("Neg").innerHTML = Math.trunc(-14.95);
    document.getElementById("Neg_Dec").innerHTML = Math.trunc(-14.05);
    document.getElementById("Str").innerHTML = Math.trunc("JavaScript");
    document.getElementById("Null").innerHTML = Math.trunc(null);
  </script>
</body>
</html>
JavaScript TRUNCATE Function