How to Print a Number with Commas as Thousands Separators in JavaScript

Here are the three ways to print a number with commas as thousands separators in JavaScript:

  1. Using “Intl.NumberFormat()” method
  2. Using “toLocaleString()” method
  3. Using the “replace()” method with “regex”

Method 1: Using the “Intl.NumberFormat()” method

The Intl.NumberFormat() method is used to represent numbers in language-sensitive formatting. It represents the currency or percentages according to the locale specified.

The locales parameter of this object is used to specify the format of the number. The “en-US” locale is used to specify that the locale takes the format of the United States and the English language, where numbers are represented with a comma between the thousands.

Syntax

Intl.NumberFormat(locales, options)

Parameters

  1. “locales”: It refers to the specific format of the language.
  2. “options”: It corresponds to the object comprising the properties.

Example

let number = 1234567.89;
let formatted = new Intl.NumberFormat().format(number);

console.log(formatted);

Output

1,234,567.89

Method 2: Using the “toLocaleString” method

The toLocaleString() method in JavaScript is used to return a string with a language-sensitive representation of a number. The optional “locales” parameter is used to specify the format of the number.

Syntax

toLocaleString(locales, options)

Parameters

  1. “locales”: It refers to the language format that needs to be used.
  2. “options”: It is an object where the properties can be set.

Example

let number = 1234567.89;
let formatted = number.toLocaleString();

console.log(formatted);

Output

1,234,567.89

Method 3: Using the “replace” method with “regex”

The replace()” method is used to search a specific string for the value and replaces it with the new value, and the “regex” pattern does a global search based on the condition as its parameter.

Syntax

string.replace(searchValue, newValue)

Parameters

  1. “searchValue”: It refers to the value that needs to be searched.
  2. “newValue”: It corresponds to the value that needs to be replaced.

Example

We will take a number as a string.

let number = "1234567.89";
let formatted = number.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

console.log(formatted);

Output

1,234,567.89

That’s it.

Leave a Comment