Format a number with commas in JavaScript
Beginner · 3 min read
1234567 is hard to read at a glance. 1,234,567 is easy. Prices, bank balances, follower counts and dashboards all show big numbers with separators between each group of three digits, called the thousands.
In this tutorial you will format numbers with JavaScript's built-in tools, toLocaleString and Intl.NumberFormat, and see why you should always tell them which country's style to use. Then you will look at the hand-written regular expression version people often copy, and where it breaks. You need to know what a number, a string and a function are.
Locales: one number, many styles
Different countries write numbers differently. In Nigeria and the US, one thousand two hundred and thirty-four and a half is written 1,234.5. In Germany it is 1.234,5: the comma and the dot swap jobs.
A locale is a short code that names one of these styles, like 'en-NG' (English, Nigeria) or 'de-DE' (German, Germany). JavaScript's formatting tools take a locale and do the grouping for you:
console.log((1234.5).toLocaleString('en-NG')); // 1,234.5
console.log((1234.5).toLocaleString('de-DE')); // 1.234,5
The brackets around 1234.5 are needed because a dot straight after a number would be read as a decimal point.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
48 Format a number with thousands separators
easyPrint a large number with separators between the thousands. Use the built-in tool and note what it gives you beyond commas.
Stuck? Three hints, smallest first
- 1.
toLocaleString()is the built-in and handles grouping for you. - 2. Pass a locale explicitly, or the output depends on the reader’s machine and cannot be tested.
- 3.
Intl.NumberFormatis the same engine and is faster if you format many numbers.
Step 1: group with toLocaleString
Wrap the call in a small function so every number in your app uses the same locale:
const grouped = (n) => n.toLocaleString('en-NG');
console.log(grouped(1234567)); // 1,234,567
console.log(grouped(1234.5)); // 1,234.5
console.log(grouped(999)); // 999
console.log(grouped(-4500)); // -4,500
Small numbers are left alone, the decimal point is kept, and the minus sign is handled for you.
Step 2: why you must pass the locale
You can call toLocaleString() with nothing in the brackets. Then it uses the settings of whoever is running the code. A reader in Nigeria sees 1,234.5 and a reader in Germany sees 1.234,5, from the same line of code.
That is correct behavior for a reader, but it means you can't write a check that says "this should print 1,234.5", because the answer depends on the machine. Naming the locale makes the output the same everywhere.
Step 3: format money with Intl.NumberFormat
toLocaleString is a shortcut for Intl.NumberFormat, the full formatting tool. Create a formatter once with your options, then call format on each number:
const naira = new Intl.NumberFormat('en-NG', {
style: 'currency',
currency: 'NGN',
maximumFractionDigits: 0,
});
console.log(naira.format(18000)); // ₦18,000
style: 'currency' adds the currency symbol, currency: 'NGN' picks the naira, and maximumFractionDigits: 0 leaves off the kobo. If you format a long list of prices, build the formatter once and reuse it: creating it is the slow part, and calling format is quick.
Step 4: the regular expression version
You will also see digits grouped by hand with a regular expression, a pattern for searching text. This one is widely copied:
const byRegex = (n) => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
console.log(byRegex(1234567)); // 1,234,567
In plain words, it finds every spot between two digits (\B) that has a multiple of three digits after it ((\d{3})+) with no more digits beyond ((?!\d)), and puts a comma there.
It works for whole numbers. Now give it more decimals:
const byRegex = (n) => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
console.log(byRegex(1234.5)); // 1,234.5
console.log(byRegex(1234.5678)); // 1,234.5,678
The pattern doesn't know about the decimal point, so it groups the digits after it too. 1234.5 only looks right because there is a single digit after the point. The built-in tools know where the point is, and they know about locales and currencies too.
The full solution
The answer panel has grouped, the naira formatter and the regex version, and prints each one. The checks cover millions, decimals, small numbers, zero, a negative and the currency symbol. Press Run to see the output.
// Always pass the locale: without it the output depends on the machine,
// so the same code prints 1,234.5 for one reader and 1.234,5 for another.
const grouped = (n) => n.toLocaleString('en-NG');
// Reuse a formatter when doing many numbers: constructing one is the slow part.
const naira = new Intl.NumberFormat('en-NG', {
style: 'currency',
currency: 'NGN',
maximumFractionDigits: 0,
});
console.log(grouped(1234567));
console.log(grouped(1234.5));
console.log('as currency:', naira.format(18000));
// The hand-rolled version, for comparison. Works, but only for plain grouping.
const byRegex = (n) => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
console.log('by regex:', byRegex(1234567));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('millions are grouped', grouped(1234567), '1,234,567');
test('a decimal keeps its point', grouped(1234.5), '1,234.5');
test('small numbers are unchanged', grouped(999), '999');
test('zero', grouped(0), '0');
test('the regex version agrees for whole numbers', byRegex(1234567), '1,234,567');
test('but it mangles decimals', byRegex(1234.5), '1,234.5');
test('currency formatting adds the symbol', naira.format(18000).includes('18,000'), true);
test('negatives are handled', grouped(-4500), '-4,500');
Passing the locale is the detail that matters. toLocaleString() with no argument uses the reader's own settings, so the same code produces 1,234.5 in Nigeria and 1.234,5 in Germany — correct behaviour, and untestable. Naming the locale makes the output deterministic. And if you are formatting a list, build one Intl.NumberFormat and reuse it; constructing it is far more expensive than calling it.
Common mistakes
- Calling
toLocaleString()with no locale. The output changes from machine to machine, so it can't be tested and may surprise your readers. - Doing math on the result.
grouped(1234)is the text'1,234', andNumber('1,234')isNaN. Format only at the moment you display the number. - Trusting the regex with decimals. It puts commas after the decimal point once there are four or more digits there.
Try it yourself
- Format
2500000as US dollars withIntl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }). - Format the same number in the
'en-IN'locale and compare where the commas go. - Use
{ notation: 'compact' }to show1234567in a short form, as follower counts do.