JavaScript

How to Format a Number With Commas as Thousand Separators?

While performing conversions in JavaScript, there can be a requirement to apply it in a specific manner. For instance, denoting a complex number such that it becomes easy to understand. In such scenarios, formatting a number with commas as the thousand separators in JavaScript assists in counting and analyzing the resultant outcome effectively.

This blog will state the approaches to format a number with commas as the thousand separators in JavaScript.

How to Format/Configure a Number in JavaScript With Commas as Thousand Separators?

For formatting/Configuring a number with commas as thousand separators in JavaScript, consider the following approaches:

Method 1: Format/Configure a Number With Commas as Thousands Separator Using the toLocaleString() Method in JavaScript

The “toLocaleString()” method gives a Date object in string form. This method is used to format a number based on the specified language format.

Syntax

document.toLocaleString(locales, options)

In this syntax:

  • locales” refers to the language format that needs to be used.
  • options” is an object where the properties can be set.

Example

Let’s go through the below-stated example:

<script>
 let n = 4232579209;
 console.log('The Given Number is : ' + n);
 let num = n.toLocaleString("en-US");
 console.log('The Output of Given Number is : ' + num);
</script>

In the above code lines.

  • Firstly, store the number in the variable named “n”.
  • In the next step, apply the “toLocaleString()” method and assign the language format as “en-US” .
  • This will, resultantly, display the specified number in the stated format separated by commas.

Output

In the output, it can be seen that the commas are included in the provided number based on the specified format.

Method 2: Format/Configure a Number With Commas as Thousands Separator via format() Method and Intl.NumberFormat() Constructor in JavaScript

The “format()” method gives a string that is formatted based on parameters provided in the “Intl” and the “Intl.NumberFormat()” constructor creates the Intl.NumberFormat objects that configure the language-sensitive number formatting. These approaches can be utilized for formatting the provided number based on a particular language format.

Syntax

Intl.NumberFormat(locales, options)

In the above-given syntax:

  • locales” refers to the specific format of the language.
  • options” correspond to the object comprising the properties.

Example

Let’s have a look at the below-stated example:

<h5 id="myNum"></h5>
<script>
 let n = prompt('Enter number : ' + '')
 let formatter = Intl.NumberFormat('en-US')
 let formatted = formatter.format(n);
 document.getElementById("myNum").innerHTML = 'The Output is : ' + formatted;
</script>

Here:

  • In the HTML code, include a heading that will display the formatted number.
  • In the JS code, input the number from the user that needs to be formatted via prompt.
  • In the next step, apply the “NumberFormat()” constructor to create an object having the stated language format, i.e., (en-US)
  • After that, apply the “format()” method that returns the resultant number based on the specified format.
  • Lastly, access the included heading using the “getElementById()” method and display the outcome via heading using the “innerHTML” property.

Output

It can be observed that the user-defined number is formatted based on the specified language format.

Method 3: Format a Number With Commas as Thousands Separator in JavaScript Using replace() Method and Regular Expression Pattern

The “replace()” method searches a particular string for the value and replaces it with the new value, and the “Regular Expression” pattern does a global search based on the condition as its parameter. These approaches can be applied to search for the digits globally and place the commas at the specified indexes.

Syntax

string.replace(searchValue, newValue)

In the above syntax:

  • searchValue” refers to the value that needs to be searched.
  • newValue” corresponds to the value that needs to be replaced.

RegEx pattern “/\B(?=(/d{3})+(?!\d))/g” For Global Search

  • /../g”: It enables the creation of a regular expression that matches every instance of a pattern.
  • \B”: It signifies that the first number in the string does not match.
  • (?=(…))”: It provides a forward-looking analysis.
  • (/d{3})”: It captures three digits.
  • (?!\d)”: It does a backward look and corresponds to something that isn’t digit-followed.

Example

Let’s go through the below-given example:

<label for="Value">Enter the Number</label>
<input type="number" id="myInput" value="">
<button onclick="myFunction()">Submit</button>
<p id="myAnswer"></p>
<script>
function myFunction() {
 let num = document.getElementById('myInput').value;
 let z = num.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
 document.getElementById('myAnswer').innerHTML = 'The Output : ' + z;
}
</script>

In the above code snippet:

  • Firstly, include the “<label>” tag to specify a label.
  • In the next step, include an “<input>” element that will take the input as “numbers” only.
  • Also, create a button having an attached “onclick” event to invoke the function named “myFunction()”.
  • The added “<p>” tag is specified to contain the resultant outcome.
  • In JavaScript code, declare a function named “myFunction()”.
  • In the function definition, access the allocated “input” field via the “getElementById()” method.
  • After that, apply the “replace()” method along with the Regular Expression pattern to format/Configure the specified number with the commas after three places.
  • Finally, access the “<p>” tag by its “id” using the “getElementById()” method and append the resultant outcome in it.

Output

In this particular output, it is evident that the regular expression came into effect properly and the number is formatted with commas at every thousand occurrences.

Conclusion

For formatting/configuring a number with commas as thousand separators using JavaScript, use the “toLocaleString()” method, the “format()” method with the “Intl.NumberFormat()” constructor, or the “replace()” method with “Regular Expression” pattern. The first two approaches simply format the provided number and user-defined number based on the particular language format. The last approach globally searches for the value and replaces it based on the regular expression pattern. This article discussed the approaches to format/Configure a number with commas as thousand separators using JavaScript.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.