JavaScript number format comma | HTML format number thousands separator

How to JavaScript number format comma?

OR

HTML format number thousands separator

It’s an very easy to do it: There is a built in function for this,

You can use The toLocaleString() method to return a string with a language-sensitive representation of a number Or Regular Expressions.

(70704567.89).toLocaleString('en')            // for numeric input
parseFloat("7800089.89").toLocaleString('en')  // for string input

Complete example of convert format number into thousands comma separator.

<html>  
<head>  
    <title>Sample Code</title>  
    <script type="text/javascript">  
  	var a = (70704567.89).toLocaleString('en')            // for numeric input
	var b = parseFloat("7800089.89").toLocaleString('en')  // for string input

	console.log(a);
	console.log(b);
    </script>  
</head>  
</html>  

Output:

Let’s do it with RegEx

You can write a JavaScript function to print an integer with commas as thousands of separators using RegEx (Regular Expressions).

<html>  
<head>  
    <title>Sample Code</title>  
    <script type="text/javascript">  
  	function thousands_separators(num)
  {
    var num_parts = num.toString().split(".");
    num_parts[0] = num_parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return num_parts.join(".");
  }

	console.log(thousands_separators(1000));
	console.log(thousands_separators(10000.23));
	console.log(thousands_separators(100000));
    </script>  
</head>  
</html>  

Output:

HTML format number thousands separator

Do comment if you have an any doubts and suggestions on this tutorial/

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.