Skip to content

JavaScript format number 2 decimals | Example code

  • by

Use toFixed() method to format number 2 decimals in JavaScript. You have to add the parameter of the toFixed() method to 2, to get the number with two decimals.

number.toFixed(x)

This method formats a number with a specific number of digits to the right of the decimal. A string representing the given number using fixed-point notation.

Example format number 2 decimals in JavaScript

Simple example code parse float with two decimal places in JavaScript. If the number of decimals is higher than in the number, zeros are added.

<!DOCTYPE html>

<body>
  <script>
   var num1 = 4.6;
   var num2 = 177.1234;

   console.log(num1.toFixed(2))
   console.log(num2.toFixed(2))
 </script>
</body>
</html>

Output:

JavaScript format number 2 decimals

More example

var num1 = parseFloat("10.547892")
var num2 = parseFloat("10.547892").toFixed(2)


console.log(num2);

Do comment if you have any doubts or suggestions on this Js format topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading