Skip to content

JavaScript number format comma | HTML format number thousands separator

  • by

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

Discover more from Tutorial

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

Continue reading