How to round a number to N decimal places in JavaScript
In this tutorial, we are going to learn about How to round a number to N decimal places in JavaScript using the toFixed()
method.
Consider we have a number like this.
const num = 12.1390
Now, we need to format the above number to 3 decimal places like this 12.139
.
Using toFixed() method
To round a number to N decimal places in JavaScript, we can use the toFixed()
method by passing N
as a argument to it.
N is number of decimal places we need to round.
The toFixed()
method takes the number of digits as argument and formats the number into the mentioned decimal places. By default the toFixed()
method removes the fractional part.
Let’s see an example:
const num = 12.1390
// 3 decimal palces
console.log(num.toFixed(3)); // "12.139"
In the example, above we have passed the 3
as an argument to the toFixed()
method. So that it rounds a number to 3 decimal places.
Note: The toFixed()
returns string representation of number.
We need to convert the string back to a number by adding +
operator.
console.log(+num.toFixed(3)); // 12.139
In the above example, we have a number but in case if you have string representation of number first convert it to number using the Number()
method then call a toFixed() method on it.
const code = '23.19055';
const result = Number(code).toFixed(3);
console.log(result); // 23.190