Explain Codes LogoExplain Codes Logo

How to format a number with commas as thousands separators?

javascript
number-formatting
javascript-functions
regex-performance
Nikita BarsukovbyNikita Barsukov·Oct 25, 2024
TLDR

Easily format number thousands with commas in JavaScript, either by using the native Number.prototype.toLocaleString() method:

const formattedNumber = (1234567).toLocaleString(); // So "1234567" transforms into "1,234,567" like magic!

Alternatively, build a regex pattern for environments which lack localization support:

const formatWithCommas = (num) => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); const formattedNumber = formatWithCommas(1234567); // "1234567" says hello to its new friends, ","!

toLocaleString() serves most cases, or opt for regex for complete control. In either case, you've got yourself a comma-formatted string.

Working with floats

Floats need special attention. We split at the decimal, apply the comma formatting to the integer part, and then rejoin the two:

function numberWithCommas(x) { var parts = x.toString().split("."); // No commas after the decimal, please! parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); return parts.join("."); } const formattedFloat = numberWithCommas(12345.6789); // Result is "12,345.6789"

Enhanced regex and performance

With modern JavaScript, you've got lookbehind assertions in your regex toolkit. It's like having a regex time machine, letting you peek at what's behind your match. Use it for performance-enhanced, finer control, especially when benchmarking talks numbers:

let number = 9876543.21; // It's a bird, it's a plane, it's Intl.NumberFormat to the rescue! console.log(new Intl.NumberFormat('en-US').format(number)); // Deploys "9,876,543.21"!

Precision for financial applications

When counting every cent matters, ensure exact decimal places using Intl.NumberFormat options:

const formatter = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, // We take care of your cents... maximumFractionDigits: 2, // ...and we promise precision! }); console.log(formatter.format(1234)); // "1,234.00" presented with two shiny decimal spaces!

But don't lose sleep over JavaScript's max safe integer limit (9,007,199,254,740,991). Just something to keep in mind for really, really big numbers.

Localization: The (number) world tour

Different locales, different number formats. With toLocaleString(), your numbers will feel right at home, anywhere:

console.log(number.toLocaleString('de-DE')); // "1.234.567". In Germany, even the numbers love their beer, hence the use of '.'

Ensure commas in all weathers by specifying the 'en-US' locale.

DIY number formatting function

Crave full customization control - separators, precision? Then, number_format(), in true PHP homage, is the function just for you:

function number_format(number, decimals, decPoint, thousandsSep) { // think of it as your personal number designer... }

Performance testing: The gladiator arena

Feeling competitive? Test methods like .replace() with regex and the dashing toLocaleString() in stack snippets or JSFiddle. Set browsers as your arena, hit the run button, and let the best method win!

Compatibility: The good ol' days

Legacy browsers need love too, or at least functions like parseFloat() and toFixed() which work well with them. Kinda their comfort food.

Library rules: When you need extra muscle

When the going gets tough, the tough call in Numeral.js. Invoking advanced number formatting, it's exactly what the formatting doctor ordered.

const numberWithCommas = numeral(1234567).format('0,0'); // "1,234,567" No sweat!

For an extra shot of formatting steroids, check out Intl.js, the Node.js friendly buddy.

The number precision operation

In number_format(), toFixed() is your trusted decimal precision scalpel. But beware of sneaky floating-point inaccuracies!

function toFixedFix(n, prec) { var k = Math.pow(10, prec); return Math.round(n * k) / k; // Just the right cut! }

Let toFixedFix manage decimal cases in number_format(). Precision now in your control.