Use the toFixed() method in JavaScript to format a number with two decimals. The toFixed() method formats a number with a specific number of digits to the right of the decimal. It returns a string representation of the number that does not use exponential notation and has the exact number of digits after the decimal place.
Example
You can try to run the following code to format a number with two decimals. Add the parameter of the toFixed() method to 2, for getting number with two decimals −
Live Demo
<html> <head> <title>JavaScript toFixed() Method</title> </head> <body> <script> var num1 = 4.6; var num2 = 177.1234; document.write("num1.toFixed() is : " + num1.toFixed(2)); document.write("<br />"); document.write("nu2m.toFixed() is : " + num2.toFixed(2)); document.write("<br />"); </script> </body> </html>
Output
num1.toFixed() is : 4.60 nu2m.toFixed() is : 177.12