In JavaScript, to always round a number up, we can do this very easily by using the Math.ceil() method.
var num = Math.ceil(1.6);
The above code would round the number 1.6 UP to 2.
We have already written a post about the Math.ceil() method which you can learn more about here. However, with the ceil() method, it will only round a number up to the integer. What we want to take a look at is how to round up to a certain decimal place.
To do this, we just need to add an extra step to the code above. If we want to round up to the first decimal place, we have to multiply the number by 10 in the ceil function, and then divide that number by 10. Here is what it would look like below.
var num = Math.ceil(num*10)/10;
We want to round the number 2.34 up to the first decimal place. So let’s enter it in the code above.
var num = Math.ceil(2.34*10)/10;
So the result of the code above would be:
2.4
Let’s see this in action in the example below.
How to Round Up to a Certain Decimal Place in JavaScript
Below we will provide code to let the user input a number, and then use the Math.ceil() method to round the number up. We will also let the user select how many decimal places they want to round the number up to. Here is our HTML setup:
Type a number with a decimal you want to round up:
Type the decimal place you want to round up to:
Below is the JavaScript and jQuery code which take the user input using the jQuery click() method, and use the Math.ceil() method on that user input and update the results below using the jQuery text() method.
Since we added the ability for the user to enter in the decimal place they want to round to, we have to add a bit more code.
The math is pretty simple, if the user wants to round to the tenth place, they enter 1. If they want to round to the hundredth place, they enter 2.
We will take whatever number they enter for this and use it as we did in the code above. We will also need the help of the Math.pow() method to do this. To make sure they don’t enter a number below 1, we will add an if else check and just use the regular ceil method result if it is below 1.
Here is the JavaScript code:
$("#submitNum").click(function(){
var num = $("#userVal").val();
var decimalPlace = $("#userVal2").val();
//If number is below 0, just run the ceil function as is
if ( decimalPlace < 1 ){
$("#results").text(Math.ceil(num));
} else {
$("#results").text(Math.ceil(num*(Math.pow(10, decimalPlace)))/(Math.pow(10, decimalPlace)));
}
});
The final code and output for this example are below:
Code Output:
Type a number with a decimal you want to round up:
Type the decimal place you want to round up to:
Full Code:
Type a number with a decimal you want to round up:
Type the decimal place you want to round up to:
Hopefully this article has been useful in helping you understand how to in JavaScript round up.
Click here to learn more.