JavaScript - How to Format a number to 2 decimal places
In this tutorial, we are going to learn about how to format a number to 2 decimal places in JavaScript using toFixed()
method.
Consider we have a number like this.
const num = 1.1290
Now, we need to format the above number to 2 decimal places like this 1.12
.
Using toFixed() method
To format a number to 2 decimal places in JavaScript, we can use the toFixed()
method by passing the 2 as a argument to it.
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 = 1.1290
// 2 decimal places
console.log(num.toFixed(2)); // " 1.12"
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(2)); // 1.12
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 = '2.19055';
const result = Number(code).toFixed(2);
console.log(result); // 2.19