JavaScript truncate

The JavaScript truncate function (trunc(x)) is a Math function. The trunc function removes the decimal values from specified expressions and returns 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 positive or negative, the trunc function will return the truncated value.
  • If it is not a number, the trunc function will return NaN; 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 JavaScript truncate function 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 the JS trunc math method on Null value, which 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