The JavaScript trunc method will remove the decimals of a number and return just the integer, using the **Math.trunc()** method.

`var num = Math.trunc(9.31);`

The above code would return the number 9.

Some other examples of Math.trunc() are below:

```
var num = Math.trunc(1.123);
var num1 = Math.trunc(.6789);
var num2 = Math.trunc(1020.12);
var num3 = Math.trunc(-.54);
var num4 = Math.trunc(-50.98283);
```

Which would result in the following:

```
1
0
1020
0
-50
```

## Math.trunc() in action using jQuery

Below we will provide code to let the user input a number, and then use the **Math.trunc()** method on that number. Here is our simple HTML setup:

```
<p>Type a number you want to use the Math.trunc() method on below:</p>
<input id="userVal" type="text" value="">
<input id="submitNum" type="submit" value="Submit">
<div id="results"></div>
```

Below is the JavaScript and jQuery code which take the user input using the jQuery **click()** or **on() keypress** methods, and use the Math.trunc() method on that user input and update the results below using the jQuery **text()** method.

```
$('#userVal').on('keypress',function(e) {
if(e.which == 13) {
$("#results").text(Math.trunc($("#userVal").val()));
}
});
$("#submitNum").click(function(){
$("#results").text(Math.trunc($("#userVal").val()));
});
```

The final code and output for this example is below:

Code Output:

Type a number you want to use the Math.trunc() method on below:

Full Code:

```
<p>Type a number you want to use the Math.trunc() method on below:</p>
<input id="userVal" type="text" value="">
<input id="submitNum" type="submit" value="Submit">
<div id="results"></div>
<script>
$('#userVal').on('keypress',function(e) {
if(e.which == 13) {
$("#results").text(Math.trunc($("#userVal").val()));
}
});
$("#submitNum").click(function(){
$("#results").text(Math.trunc($("#userVal").val()));
});
</script>
```

Hopefully this article has been useful in helping you understand how the JavaScript Math.trunc() method works.

## Leave a Reply