Skip to content

JavaScript format number with commas | Example code

  • by

Use Number.toLocaleString() method to format number with commas in JavaScript. This is a built-in method to transform a number value into a comma-separated string.

Example format number with commas in JavaScript

Simple example code pass “en-US” as the parameter so that it will always create a thousand separator for your number.

<!DOCTYPE html>

<body>
  <script>
   let n = 10200300;
   let str = n.toLocaleString("en-US");

   console.log(str);
 </script>
</body>
</html>

Output:

JavaScript format number with commas

You can use the same method for floating numbers to format with commas.

<script>
   let n = 10200300.5555;
   let str = n.toLocaleString("en-US");

   console.log(str);
</script>

Output: 10,200,300.556

JS Format number with commas using regular expressions

Using regular expressions able to find and replace values in a given string and format it. For example, consider the following regex pattern:

/\B(?=(\d{3})+(?!\d))/g

Code

Use the regex pattern in combination with the String replace() function to replace the markers with commas.

<script>
    let n = numberWithCommas(234234.555);
    num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');

    console.log(n); // "234,234.555"
</script>

How to print a number with commas as thousands of separators in JavaScript?

Answer: Use RegEx with replace method.

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

Do comment if you have any doubts or suggestions on this JS formate program.

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