Format Numbers with Commas in JavaScript
Introduction
Handling numbers in different formats is a common task for many developer, especially those working with UI/UX. One of those tasks is displaying numbers in a more human-readable form, like separating digits with commas. Whether it's for a financial application, displaying stats on a dashboard, or merely making large numbers more digestible, formatting numbers with commas can help improve user experience. In this article, we'll explore various ways to perform this task, even throwing in a couple of popular library methods to make the job easier.
Native JavaScript Methods
One of the simplest ways to format numbers with commas is by using the native toLocaleString
method:
const number = 1234567.89;
const formattedNumber = number.toLocaleString();
console.log(formattedNumber); // Outputs: "1,234,567.89"
This method automatically formats the number according to the user's locale, making it an excellent choice for internationalization. For my locale, it uses commas after every third digit.
Note: We're used to seeing numbers, like the one shown above, presented with only two digits after the decimal when displayed as currency. However, keep in mind that toLocaleString()
will keep all digits after the decimal. So 1234567.890123
would become "1,234,567.890123".
Using Regular Expressions
If you need a bit more control over the formatting, regular expressions can help:
function formatNumberWithCommas(number) {
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
const number = 1234567.89;
console.log(formatNumberWithCommas(number)); // Outputs: "1,234,567.89"
Link: This function uses regular expressions to insert commas after every third digit from right to left, providing the desired formatting. Regular expressions are a powerful tool, but they might seem complex to those unfamiliar with them. You can read more about regular expressions in JavaScript in our article, Guide to Regular Expressions and Matching Strings in JavaScript.
Using the Lodash Library
If you prefer using libraries and happen to be a fan of Lodash, the popular utility library provides a _.comma
method which can do the job:
const _ = require('lodash');
const number = 1234567.89;
const formattedNumber = _.comma(number);
console.log(formattedNumber); // Outputs: "1,234,567.89"
Conclusion
Formatting numbers with commas is a common requirement, enhancing the readability and overall user experience. While JavaScript provides native methods like toLocaleString
, you can also achieve this through regular expressions or even employ libraries like Lodash. The approach you choose may depend on your specific needs and the context in which you're working. What's important is that you now have the tools at your disposal to make those large, unwieldy numbers a little more friendly to the human eye.