230 words
1 minutes
How to Format Numbers with Commas in JavaScript
In JavaScript, formatting numbers with commas can be achieved using different approaches. Here are some common methods:
1. Using toLocaleString()
The toLocaleString()
method is the simplest and most reliable way to format numbers with commas, especially when dealing with localization. It formats a number according to the locale and options you provide.
const number = 1234567.89;
const formattedNumber = number.toLocaleString("en-US");
console.log(formattedNumber); // Output: "1,234,567.89"
Options for toLocaleString()
: You can customize the formatting further using options.
const number = 1234567.89;
const options = {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
};
const formattedNumber = number.toLocaleString("en-US", options);
console.log(formattedNumber); // Output: "1,234,567.89"
2. Using Regular Expressions
If you need a custom solution or want to format numbers without relying on localization, you can use regular expressions:
function formatNumberWithCommas(number) {
const [integer, decimal] = number.toString().split(".");
const integerWithCommas = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return decimal ? `${integerWithCommas}.${decimal}` : integerWithCommas;
}
const number = 1234567.89;
const formattedNumber = formatNumberWithCommas(number);
console.log(formattedNumber); // Output: "1,234,567.89"
3. Using a Custom Function
You can also create a custom function to handle formatting:
function addCommas(num) {
const parts = num.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
const number = 1234567.89;
const formattedNumber = addCommas(number);
console.log(formattedNumber); // Output: "1,234,567.89"
Choosing the Right Method
toLocaleString()
: Best for standard use cases, especially when localization or internationalization is needed.- Regular Expressions or Custom Functions: Useful for specific formatting requirements or environments where localization features are not available.
Each method has its own use cases, so choose the one that best fits your needs!