Emmanuel Akinfulubi

JavaScriptString

Add thousands separators manually in JavaScript

Intermediate · 4 min read

1000000 is hard to read. 1,000,000 is easy. Those commas are thousands separators, and every price, bank balance and statistic on the web uses them. In real code you would call toLocaleString() and be done, but writing it yourself once teaches you a lot about strings, and shows you why a popular shortcut you will find online is broken.

In this tutorial you will write group(n), which turns 4500 into '4,500', keeps a minus sign in front and leaves the decimal part alone. You should know String(), split, slice and a for loop. The remainder operator % is explained below.

Where the commas go

Count digits from the right. A comma goes in front of every group of three. In 1234567, that is before 234 and before 567: 1,234,567.

Counting from the left is easier in a loop, so turn the rule round. For the digit at position i, the number of digits from it to the end is digits.length - i. If that number is a multiple of three, and it isn't the very first digit, a comma goes before it.

The remainder operator

a % b gives the remainder after dividing a by b. 6 % 3 is 0, 7 % 3 is 1. "Is a multiple of three" is the same as "x % 3 === 0".

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

50 Thousands separators, by hand

fair

Format 4500 as '4,500' and 1000000 as '1,000,000' without using toLocaleString. Then check what your answer does to a decimal.

Stuck? Three hints, smallest first
  1. 1. Separate the whole part from the fraction before you start grouping.
  2. 2. A comma goes before every position whose distance from the end is a multiple of three.
  3. 3. The popular regex one-liner has a bug, and a decimal fraction is where it shows.

Step 1: commas in a whole number

Step 1

const digits = '1000000';
let out = '';
for (let i = 0; i < digits.length; i++) {
  if (i > 0 && (digits.length - i) % 3 === 0) out += ',';
  out += digits[i];
}
console.log(out); // '1,000,000'

At i = 1 there are six digits left, a multiple of three, so a comma goes in. At i = 4 there are three left, so another comma. i > 0 stops a comma being added before the first digit of a number like 123456.

Step 2: separate the decimal part

A number like 1234.5678 has a fraction after the dot. Only the whole part gets commas, so split it off first:

Step 2

const [whole, fraction] = String(1234.5678).split('.');
console.log(whole);    // '1234'
console.log(fraction); // '5678'
console.log(String(4500).split('.')); // [ '4500' ]

const [whole, fraction] = ... is destructuring: it takes the first two items of the array and names them. A whole number has no dot, so the array has only one item and fraction is undefined.

Step 3: keep the minus sign out of the way

Step 3

const whole = '-4500';
const sign = whole.startsWith('-') ? '-' : '';
const digits = sign ? whole.slice(1) : whole;
console.log(sign, digits); // - 4500

If the minus sign stayed in, it would be counted as a digit, and -450 would come out as -,450. So we take it off, group the digits, and put it back at the end.

Step 4: the whole function

Step 4

function group(n) {
  const [whole, fraction] = String(n).split('.');
  const sign = whole.startsWith('-') ? '-' : '';
  const digits = sign ? whole.slice(1) : whole;
  let out = '';
  for (let i = 0; i < digits.length; i++) {
    if (i > 0 && (digits.length - i) % 3 === 0) out += ',';
    out += digits[i];
  }
  return sign + out + (fraction ? '.' + fraction : '');
}
console.log(group(4500));      // '4,500'
console.log(group(1000000));   // '1,000,000'
console.log(group(999));       // '999'
console.log(group(0));         // '0'
console.log(group(-4500));     // '-4,500'
console.log(group(1234.5678)); // '1,234.5678'

The last line puts the dot and the fraction back only if there was one, so whole numbers don't get a stray . at the end.

Step 5: the popular one-liner, and its bug

Search online and you will find this regex version:

Step 5

const byRegex = (n) => String(n).replace(/\B(?=([0-9]{3})+(?![0-9]))/g, ',');
console.log(byRegex(4500));      // '4,500'
console.log(byRegex(1000000));   // '1,000,000'
console.log(byRegex(1234.5678)); // '1,234.5,678'

It works on every whole number, so it passes casual testing. Then a price with decimals comes along and it puts a comma inside the fraction. 1,234.5,678 isn't a number anyone can read.

Here is why. The pattern means "a position inside a run of word characters, followed by groups of exactly three digits and then something that isn't a digit". The digits after the dot, 5678, match that rule just as well as the ones before it. The regex has no idea where the dot is.

Our group function avoids the problem because it splits on the dot first and only ever groups the whole part.

Step 6: what to use in real code

Step 6

console.log((4500).toLocaleString('en-US'));    // '4,500'
console.log((1000000).toLocaleString('en-US')); // '1,000,000'

toLocaleString and Intl.NumberFormat know the rules for each language. Not every country groups in threes, and many use a dot or a space as the separator instead of a comma. Use the built-in for anything users see. Write it by hand to learn how it works.

The full solution

The panel has group and the regex one-liner, and prints both on the same decimal number. Press Run and compare the last two lines, then read the checks underneath.

The answer

function group(n) {
  const [whole, fraction] = String(n).split('.');
  const sign = whole.startsWith('-') ? '-' : '';
  const digits = sign ? whole.slice(1) : whole;

  let out = '';
  for (let i = 0; i < digits.length; i++) {
    if (i > 0 && (digits.length - i) % 3 === 0) out += ',';
    out += digits[i];
  }
  return sign + out + (fraction ? '.' + fraction : '');
}

// The one-liner everybody copies. It groups every run of digits, including the
// ones after the decimal point.
const byRegex = (n) => String(n).replace(/\B(?=([0-9]{3})+(?![0-9]))/g, ',');

console.log('group(4500)          :', group(4500));
console.log('group(1000000)       :', group(1000000));
console.log('group(1234.5678)     :', group(1234.5678));
console.log('byRegex(1234.5678)   :', byRegex(1234.5678), '<- the decimals were grouped too');

Output


      
10 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 10 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

10 checks

test('four digits gain one comma', group(4500), '4,500');
test('seven digits gain two', group(1000000), '1,000,000');
test('three or fewer gain none', group(999), '999');
test('zero is left alone', group(0), '0');
test('a negative keeps its sign outside the grouping', group(-4500), '-4,500');
test('a decimal part is left ungrouped', group(1234.5678), '1,234.5678');
test('the built-in agrees on the whole numbers', (4500).toLocaleString('en-US'), '4,500');
test('the popular one-liner also works, up to a point', byRegex(4500), '4,500');
test('but it groups the DECIMALS, which is wrong', byRegex(1234.5678), '1,234.5,678');
test('splitting on the dot first is the fix', group(1234.5678).split('.')[1], '5678');

toLocaleString or Intl.NumberFormat is the right answer in real code: they know that not every locale groups in threes, and not every locale uses a comma. Writing it by hand is worth doing once to see where the popular shortcut fails.

That failure is instructive. \B(?=([0-9]{3})+(?![0-9])) means "a position inside a word, followed by some multiple of three digits and then a non-digit" — and the digits after a decimal point satisfy that perfectly. It passes every test written with an integer.

Common mistakes

  • Grouping the decimals. Split on the dot first and add commas to the whole part only.
  • Counting the minus sign as a digit. Take the sign off, group the digits, then put it back.
  • Adding a comma before the first digit. Without the i > 0 check, 123456 becomes ,123,456.

Try it yourself

  1. Add a second parameter so group(1234567, ' ') uses a space as the separator.
  2. Write ungroup('1,234.56') that turns the text back into the number 1234.56.
  3. Fix the regex version by applying it only to the part before the dot.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.