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
Using toFixed() method
toFixed() method by passing
2 as a argument to it.
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"
toFixed() returns string representation of number.
We need to convert the string back to a number by adding
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