Skip to content

JavaScript format number with commas and decimal places | Example

  • by

You have to use math round() and split to a given number to format numbers with commas and decimal places in JavaScript. RegEx is also required to do it.

JavaScript format number with commas and decimal places

A simple example code converts a given number into number value format with a comma and two decimal points.

This turns a number 1234.567 in to 1,234.567.

 <!DOCTYPE html>
 <html>
 <body>

  <script>
    var n = 1234.567;

    var val = Math.round(Number(n) *100) / 100;

    var parts = val.toString().split(".");

    var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");

    console.log(num);
    console.log(typeof(num))
  </script>

</body>
</html> 

Output:

JavaScript format number with commas and decimal places

Print a number with commas as thousands of separators in JavaScript

  <script>
    var n = 1234.567;

    function numberWithCommas(x) {
      return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    console.log(numberWithCommas(n));

  </script>

Use toLocaleString

// With custom settings, forcing a "US" locale to guarantee commas in output
let number2 = 1234.56789; // floating point example
number2.toLocaleString('en-US', {maximumFractionDigits:2}) // "1,234.57"

You can use the minimumFractionDigits option of the toLocaleString function.

// result 3,000.00
Number(parseFloat(3000).toFixed(2)).toLocaleString('en', {
    minimumFractionDigits: 2
});

// result 123,233.12
Number(parseFloat(123233.12).toFixed(2)).toLocaleString('en', {
    minimumFractionDigits: 2
});

Do comment if you have any doubts or suggestions on this JS number 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

Your email address will not be published. Required fields are marked *