How to Use toLocaleString() to Format JavaScript Numbers with Commas?

Estimated read time 1 min read

The toLocaleString() method in JavaScript can be used to format a number with commas (or other locale-specific separators) to improve readability. Here’s an example:

let number = 123456.789;
let formattedNumber = number.toLocaleString();
console.log(formattedNumber); // "123,456.789"

In this example, the number 123456.789 is passed to the toLocaleString() method, which returns a string representation of the number with locale-specific formatting, including the use of a comma as a separator.

You can also specify a locale to be used for formatting, for example:

let number = 123456.789;
let formattedNumber = number.toLocaleString('en-US');
console.log(formattedNumber); // "123,456.789"

The first argument to toLocaleString() is the locale to be used, in this case 'en-US' for US English. This allows you to format the number according to the conventions of a specific region or language.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply