JavaScript truncate

The JavaScript truncate function (trunc(x)) is a Math function. The trunc function is used to remove the decimal values from specified expressions and return the integer value. The syntax of the 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, the trunc function will return the truncated value.
  • If it is not a number, the trunc function will return NaN, and if it is Null, it will return Zero.

JavaScript truncate Function Example

The truncate Function removes the decimal values and returns the integer value. In this example, we will find the truncated values of different data types using trunc() and display the output.

  • First, we used it on the Positive Decimal values.
  • Next two statements, We used the JavaScript trunc Function on the negative Decimal numbers.
  • Next, we tried on the string text. It will return NaN (Not a Number) as output.
  • Last, we tried JS trunc math method on Null value, and it returns Zero.
<!DOCTYPE html>
<html>
<head>
    <title> JavaScriptTRUNCATEFunction </title>
</head>
<body>
  <h1> JavaScriptTRUNCFunction </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