Oftentimes, we’ve to round floating-point numbers in our JavaScript web apps.
In this article, we’ll look at how to round floating-point numbers in JavaScript.
Number.prototype.toFixed
JavaScript numbers have the toFixed method that returns a string version of the number rounded to the number of decimal places we passed in as the argument.
For instance, we can write:
const rounded = Number((6.6756854).toFixed(1));
console.log(rounded)
Then rounded is '6.7' since we passed in 1 to toFixed .
This makes it returns a string rounded to 1 decimal place.
Math.round
Another way to round floating-point numbers is to use the Math.round method.
Math.round returns the rounded number instead of a string.
So we can use it if we want to round a number and keep the returned result as a number.
For instance, we can write:
const number = 6.6756854
const rounded = Math.round(number * 10) / 10;
console.log(rounded)
If we want to round to 1 decimal place, then we multiply the number by 10.
Then we call Math.round on that number.
Then we divide by 10 to get the rounded number.
So rounded is '6.7' .
If we want to round to 2 decimal places, then we replace 10 with 100.
And if we round to 3 decimal places, we replace 10 with 1000, and so on.
Number.prototype.toPrecision
We can also use the number’s toPrecision method to return a number that’s rounded to the given decimal place.
It also returns a number instead of a string.
For instance, we can write:
const rounded = (6.6756854).toPrecision(2)
console.log(rounded)
The argument is the number of decimal places to round to.
So passing in 2 as the first argument would round the number we call it into 2 decimal places.
Therefore, rounded is 6.7.
Math.floor
We can use the Math.floor method to round a number down to the nearest integer.
For instance, we can write:
const rounded = Math.floor(6.6756854)
console.log(rounded)
Then rounded is 6.
Math.ceil
The Math.ceil method lets us round a number up to the nearest integer.
For instance, we can write:
const rounded = Math.ceil(6.6756854)
console.log(rounded)
And rounded is 7.
Conclusion
There’re various Math static methods and number instance methods that we can use to round floating-point numbers the way we like.