The trunc method in JavaScript is designed to eliminate the decimal portion of a specified number, returning solely the integer part that remains.
Syntax
The trunc function can be expressed using the following syntax:
Example
Math.trunc(num)
Parameter
num - A number.
Return
The integer part of the given number.
JavaScript Math trunc method example
In this section, we will explore the trunc method by examining a variety of examples.
Example 1
Consider the following example that demonstrates how to extract and display the integer portion of specified numbers.
Example
<script>
document.writeln(Math.trunc(12.24)+ "<br>");
document.writeln(Math.trunc(0.84));
</script>
Output:
Example 2
In this illustration, we will demonstrate the use of the trunc function with negative integers.
Example
<script>
document.writeln(Math.trunc(-12.24)+ "<br>");
document.writeln(Math.trunc(-0.84));
</script>
Output:
Output
-12
0
Example 3
In this section, you have the opportunity to evaluate the trunc method using your own custom test scenarios.
Example
<script>
function display()
{
var x=document.getElementById("num").value;
document.getElementById("result").innerHTML=Math.trunc(x);
}
</script>
<form>
Enter a number: <input type="text" id="num">
<input type="button" onclick="display()" value="submit">
</form>
<p><span id="result"></span></p>