Emmanuel Akinfulubi

JavaScriptMath

Count the digits in a number in JavaScript

Intermediate · 3 min read

How many digits does 42 have? Two. 1000? Four. Counting digits sounds too simple to get wrong, and that is exactly why this exercise is useful. You need a digit count to pad numbers to a fixed width, to format IDs, and to split a number into its parts.

In this tutorial you will count digits three ways: with String, with a logarithm, and with a division loop. Then you will find a 15-digit number where the logarithm method is off by one, and a large number where the string method is off by seventeen. You need to know loops and Math.floor.

What a logarithm tells you

Math.log10(n) answers the question "10 to the power of what gives n?". So Math.log10(100) is 2 and Math.log10(1000) is 3. For numbers in between, the answer has a decimal part:

JavaScript

console.log(Math.log10(1000)); // 3
console.log(Math.log10(42));   // 1.6232492903979006

Every 2-digit number has a log10 from 1 up to (but not including) 2. Every 4-digit number has one from 3 up to 4. So "round down, then add 1" gives the digit count. That is the formula people reach for: Math.floor(Math.log10(n)) + 1.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

45 How many digits, and where log10 lies

fair

Count the digits of an integer three ways: with String, with Math.log10, and with a division loop. Then find an input where the log10 version is off by one, and one where the String version is off by seventeen.

Stuck? Three hints, smallest first
  1. 1. Math.floor(Math.log10(n)) + 1 is the closed form, and it depends on a logarithm being exact.
  2. 2. Try 999999999999999 — fifteen nines.
  3. 3. String switches to exponential notation at 1e21, and BigInt(n).toString() never does.

Step 1: three ways to count

Step 1

const digitsByString = (n) => String(Math.abs(n)).length;
const digitsByLog = (n) => Math.floor(Math.log10(Math.abs(n))) + 1;
function digitsByLoop(n) {
  n = Math.abs(Math.trunc(n));
  let count = 0;
  do {
    count++;
    n = Math.floor(n / 10);
  } while (n > 0);
  return count;
}
console.log([7, 42, 1000].map(digitsByString)); // [ 1, 2, 4 ]
console.log([7, 42, 1000].map(digitsByLog));    // [ 1, 2, 4 ]
console.log([7, 42, 1000].map(digitsByLoop));   // [ 1, 2, 4 ]

All three strip the sign with Math.abs. The string version counts characters. The log version uses the formula above. The loop knocks one digit off the right each time with Math.floor(n / 10) and counts how many times it can do that.

Step 2: why the loop is do...while

A normal while (n > 0) loop checks the condition before it runs. For 0 it would never run, and you would get 0 digits. A do...while loop runs once first, then checks. So 0 counts as one digit, which is correct.

Step 2

console.log(digitsByLoop(0)); // 1
console.log(digitsByLog(0));  // -Infinity

The log version fails here: Math.log10(0) is -Infinity, because no power of 10 gives 0. Negative numbers would fail too, since Math.log10(-42) is NaN. That is why the formula needs Math.abs.

Step 3: do they agree?

Step 3

let firstDisagreement = 'none below 10000';
for (let n = 1; n < 10000; n++) {
  if (digitsByString(n) !== digitsByLog(n) || digitsByString(n) !== digitsByLoop(n)) {
    firstDisagreement = n;
    break;
  }
}
console.log(firstDisagreement); // none below 10000

The three agree on every number from 1 to 9999. It is tempting to stop here and trust all three. Don't.

Step 4: fifteen nines

Step 4

const nines = 999999999999999;
console.log(Math.log10(nines));   // 15
console.log(digitsByLog(nines));  // 16
console.log(digitsByLoop(nines)); // 15

The true logarithm of fifteen nines is 14.99999999999999956..., a hair below 15. JavaScript numbers can only store about 15 to 17 significant digits, and the nearest value it can store is exactly 15. Then Math.floor(15) + 1 is 16, one digit too many. A formula that is wrong for even one number can't be trusted for exact counting.

Step 5: a number too big for String

Step 5

const huge = 1e21;
console.log(String(huge));                   // 1e+21
console.log(digitsByString(huge));           // 5
console.log(BigInt(huge).toString().length); // 22

From 1e21 upward, String writes numbers in exponential notation. The string version counts the 5 characters of '1e+21', but the number really has 22 digits, so the count is 17 short. BigInt(n).toString() never shortens the digits, so it gives the true count.

The loop version gets this right too, since it never looks at text.

Step 6: a shortcut that doesn't help

You may see ~~n used to drop decimals. It only works inside 32 bits:

Step 6

console.log(~~1e10);          // 1410065408
console.log(Math.trunc(1e10)); // 10000000000

~~ converts the number to a 32-bit integer first, which scrambles anything larger than about 2.1 billion. That is why the loop uses Math.trunc.

The full solution

The answer panel has all three counters, runs the agreement check up to 10000, then prints the fifteen-nines case and the 1e21 case with its BigInt count. Press Run to see the output.

The answer

const digitsByString = (n) => String(Math.abs(n)).length;
const digitsByLog = (n) => Math.floor(Math.log10(Math.abs(n))) + 1;

function digitsByLoop(n) {
  n = Math.abs(Math.trunc(n));
  let count = 0;
  do {
    count++;
    n = Math.floor(n / 10);
  } while (n > 0);
  return count;                        // do..while, so 0 has one digit
}

const nines = 999999999999999;         // fifteen of them
const huge = 1e21;

let firstDisagreement = 'none below 10000';
for (let n = 1; n < 10000; n++) {
  if (digitsByString(n) !== digitsByLog(n) || digitsByString(n) !== digitsByLoop(n)) {
    firstDisagreement = n;
    break;
  }
}

console.log('digits of 42, 1000 :', [42, 1000].map(digitsByLoop));
console.log('all three agree to 10000?', firstDisagreement);
console.log('fifteen nines      :', nines);
console.log('log10 of it        :', Math.log10(nines), '<- rounded up to a whole number');
console.log('so log10 says      :', digitsByLog(nines), 'but there are', digitsByLoop(nines));
console.log('String(1e21)       :', String(huge), 'length', digitsByString(huge));
console.log('BigInt(1e21)       :', BigInt(huge).toString().length, 'digits');

Output


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

9 checks

test('the loop counts 1, 2 and 4 digits, and gives 0 one digit', [7, 42, 1000, 0].map(digitsByLoop), [1, 2, 4, 1]);
test('all three methods agree on every number below 10000', firstDisagreement, 'none below 10000');
test('but Math.log10 of fifteen nines comes back as exactly 15', Math.log10(nines), 15);
test('so the closed form claims 16 digits where there are 15', [digitsByLog(nines), digitsByLoop(nines)], [16, 15]);
test('String gives up at 1e21 and reports five characters', [String(huge), digitsByString(huge)], ['1e+21', 5]);
test('while the true count is 22, which BigInt will tell you', BigInt(huge).toString().length, 22);
test('log10(0) is -Infinity, so the closed form has no answer for 0', digitsByLog(0) === -Infinity, true);
test('and a negative needs its sign stripped or log10 returns NaN', [Number.isNaN(Math.log10(-42)), digitsByLog(-42)], [true, 2]);
test('~~ truncates only inside 32 bits, so it cannot help here', [~~1e10, Math.trunc(1e10)], [1410065408, 10000000000]);

Math.floor(Math.log10(n)) + 1 is the answer everyone reaches for, and it is wrong for 999999999999999. The true logarithm is 14.999999999999999..., which is closer to 15 than to the largest double below 15, so it rounds up to exactly 15, the floor gives 15, and the count comes out one too many. One counterexample below 2 ** 53 is enough to disqualify the method for exact work.

String fails differently and more visibly: from 1e21 upwards it produces exponential notation, so the length is a fact about the notation rather than the number. The division loop has neither failure, and BigInt(n).toString().length is the version to use when the value came from outside your code. Note the do..while: a plain while (n > 0) would report zero digits for 0.

Common mistakes

  • Trusting Math.floor(Math.log10(n)) + 1. It gives 16 for fifteen nines, and -Infinity for 0.
  • Using while instead of do...while. A plain while (n > 0) reports zero digits for 0.
  • Counting characters of String(n) for big numbers. Past 1e21 you are counting the notation, not the digits.

Try it yourself

  1. Write padNumber(n, width) that adds leading zeros, so padNumber(42, 5) gives '00042'. Use digitsByLoop.
  2. Find the smallest number of nines where digitsByLog first goes wrong. (Hint: try 14 nines, then 15.)
  3. Change digitsByLoop to count the digits of a BigInt, using 10n instead of 10.

Keep practising

Newsletter

New writing, when it lands.

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