How to Format Number with Commas in JavaScript Easily
To format a number with commas in JavaScript, use the
toLocaleString() method on the number. This method converts the number into a string with commas as thousands separators automatically.Syntax
The basic syntax to format a number with commas is:
number.toLocaleString(): Converts the number to a string with commas as thousands separators based on locale.- You can optionally pass a locale string like
'en-US'to specify formatting style.
javascript
number.toLocaleString([locales[, options]])
Example
This example shows how to format a large number with commas using toLocaleString():
javascript
const number = 1234567.89; const formatted = number.toLocaleString('en-US'); console.log(formatted);
Output
1,234,567.89
Common Pitfalls
Some common mistakes when formatting numbers with commas:
- Trying to use
toString()which does not add commas. - Using string methods like
replace()without careful regex, which can be error-prone. - Not specifying locale may cause unexpected formatting in some environments.
Always prefer toLocaleString() for reliable formatting.
javascript
const num = 1234567; // Wrong way: toString() does not add commas console.log(num.toString()); // Output: 1234567 // Right way: toLocaleString() adds commas console.log(num.toLocaleString('en-US')); // Output: 1,234,567
Output
1234567
1,234,567
Quick Reference
Summary tips for formatting numbers with commas in JavaScript:
- Use
number.toLocaleString()for easy comma formatting. - Pass
'en-US'locale for standard US-style commas and decimal points. - Works for integers and decimals.
- For custom formatting, explore
Intl.NumberFormatoptions.
Key Takeaways
Use
toLocaleString() to format numbers with commas easily.Specify locale like
'en-US' for consistent comma placement.Avoid using
toString() or manual string methods for commas.This method works for both whole numbers and decimals.
For advanced formatting, consider
Intl.NumberFormat.