The easiest way to remove the decimals of a number in JavaScript is by using the Math.trunc() method.

var noDecimalNumber = Math.trunc(9.31);

We can wrap this code in a function to simplify the whole process. You simply enter in a number, and the function will return the number with no decimal places.

function noDecimalNumber(num){
  return Math.trunc(num);
};

Here are some more examples using our function:

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

Which would result in the following:

1
0
1020
0
-50

Remove Decimals of Any Number in JavaScript

Below we will provide code to let the user input a number, and then use our noDecimalNumber() function we created above to return the number without decimals. Here is our simple HTML setup:

Type a number:

Below is the JavaScript code which gets the user input using the onclick event along with the value property and then uses our noDecimalNumber() function to return the number with no decimals.

We will finally update the results below using the textContent property.

Here is the JavaScript code:

function noDecimalNumber() {
  //Get the user inputted number
  var userNum = document.getElementById("userVal").value;

  //Remove the decimal if one exists 
  var num = Math.trunc(userNum);

  //Show the result to the user to the user
  document.getElementById("results").textContent = num;   
};

The final code and output for this example are below:

Code Output:

Type a number:


Full Code:

Type a number:

Hopefully this article has been useful in helping you understand how to remove decimals from a number in JavaScript.

Categorized in:

JavaScript,

Last Update: March 22, 2024