How to format a number to specific decimal places in JavaScript
In this tutorial, we are going to learn about formatting a number to specific decimal places in JavaScript using toFixed()
method.
Consider we have a number like this.
const num = 123.1390
Now we need to format the above number according to specific decimal places like 123.12
or 123.139
.
Using toFixed() method
The toFixed()
method formats a number and returns the string representation of a number.
By default the toFixed()
method removes the fractional part.
It also accepts the optional argument called digits
which means we need to specify the number of digits after the decimal point.
Let’s see an example:
const num = 123.1390
// fractional part is removed
console.log(num.toFixed()); // "123"
Have you seen our number is converted to string representation so that we need to convert the string back to a number by adding +
operator.
console.log(+num.toFixed()); // 123
Formatting number to 2 decimal places
To format a number to 2 decimal places we need to pass 2
as an argument to the toFixed()
method.
const num = 123.1390
console.log(+num.toFixed(2)); // 123.13
Similarly, we can format a number according to our needs like this.
const num = 123.1390
// 1 decimal place
console.log(+num.toFixed(1)); // 123.1
// 2 decimal places
console.log(+num.toFixed(2)); // 123.13
// 3 decimal places
console.log(+num.toFixed(3)); // 123.139