I’m trying to display large numbers in a more readable format in JavaScript by adding commas as thousands separators. For example, I’d like a value like 1234567 to be shown as 1,234,567.
I currently have a working solution, but it feels a bit verbose and regex-heavy. I’m wondering if there’s a cleaner or more modern approach to javascript format number with commas, especially something that’s easier to read and maintain.
function addThousandsSeparator(value) {
let str = String(value);
const regex = /(\d+)(\d{3})/;
while (regex.test(str)) {
str = str.replace(regex, '$1,$2');
}
return str;
}
console.log(addThousandsSeparator(1000));
This works, but I’m curious if there’s a simpler or more elegant way to handle this.
Bonus points if the solution also works nicely with floating-point numbers, although locale-specific formatting isn’t a requirement for me.
Would love to hear how others handle this in real-world JavaScript code. Thanks!
In most cases, I just use toLocaleString() because it’s built into JavaScript and handles commas automatically. It’s super readable and works with both integers and floats:
const num = 1234567.89;
console.log(num.toLocaleString()); // "1,234,567.89"
I love this approach because it’s clean, doesn’t require any regex, and you can also tweak it if you want different separators or locales later. For basic thousands separators, it’s perfect.
If you want a bit more flexibility, especially when formatting currency or ensuring a fixed number of decimals, I usually go with Intl.NumberFormat:
const formatter = new Intl.NumberFormat('en-US');
console.log(formatter.format(1234567)); // "1,234,567"
console.log(formatter.format(1234567.89)); // "1,234,567.89"
I use this when working on bigger projects where consistency matters across different parts of the app. It’s a bit more verbose initially, but it’s reliable and scales nicely.
Sometimes, when I want a lightweight solution and don’t care about locales, I’ve done a simple one-liner using regex, shorter than a while loop:
const num = 1234567;
const formatted = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
console.log(formatted); // "1,234,567"
It’s a nice trick to know, especially if you need something quick without relying on the internationalization APIs. That said, I generally prefer toLocaleString() for readability and maintainability. For most real-world projects, toLocaleString() is the cleanest and easiest to read. Intl.NumberFormat is great when you need precise control, and regex is handy for learning or quick hacks.