
JavaScript format numbers with commas
To format numbers with commas as thousands separators in JavaScript, you can use the toLocaleString()
method available on number values. Here’s an example:
var number = 1234567;
var formattedNumber = number.toLocaleString();
console.log(formattedNumber);
In this example, the toLocaleString()
method is called on the number
variable. It formats the number with commas as thousands separators according to the user’s locale settings. The resulting formatted number is stored in the formattedNumber
variable.
When you run this code, the output will be:
1,234,567
The toLocaleString()
method has additional options to customize the formatting, such as specifying the locale or specifying options for decimal separators, grouping separators, and more. By default, it uses the user’s locale settings, but you can override them by providing the desired options.
Here’s an example that demonstrates customizing the formatting options:
var number = 12345.6789;
var options = { style: 'decimal', maximumFractionDigits: 2 };
var formattedNumber = number.toLocaleString('en-US', options);
console.log(formattedNumber);
In this example, we pass an options object as the second argument to toLocaleString()
. The style
option is set to 'decimal'
, and the maximumFractionDigits
option is set to 2
. This ensures that the number is formatted as a decimal with a maximum of 2 decimal places.
The output will be:
12,345.68
By using the toLocaleString()
method with appropriate options, you can format numbers with commas as thousands separators according to your requirements.