In JavaScript, you can use the toFixed() method to specify the number of digits you want after the decimal place. So, you can simply pass in 2 to toFixed() lead by the actual variable or constant as follows:
const someNumber = 2
const formattedNumber = someNumber.toFixed(2)
console.log(formattedNumber)
//output
2.00
Code language: JavaScript (javascript)
The above code would output 2.00. You can, of course, specify as many digits as you want like this:
const someNumber = 2;
const anotherFormattedNumber = someNumber.toFixed(5)
console.log(anotherFormattedNumber)
//output
2.00000
Code language: JavaScript (javascript)
You can also format a string with N decimal places. To do that, you’d first need to convert the string to a number. You can then chain the result with a toFixed() method as shown in the example below:
const someString = '2'
const formattedString = parseFlo1at(someString).toFixed(2)
console.log(formattedString)
//output
2.00
Code language: JavaScript (javascript)
If you have any doubts or suggestions, let me know in the comments below!