Ways of counting digits

Benchmark created by Jim on


Description

Not only is the log way of doing this slower, it'll break down on high numbers due to precision issues.

Test runner

Ready to run.

Testing in
TestOps/sec
Math.floor(Math.log(n)/Math.log(10)) + 1
function countDigits(n) {
  return Math.floor(Math.log(n)/Math.log(10)) + 1;
}

countDigits(1);
countDigits(9);
countDigits(10);
countDigits(11);
countDigits(99);
countDigits(100);
countDigits(101);
countDigits(999);
countDigits(1000);
countDigits(1001);
countDigits(9999);
countDigits(10000);
countDigits(10001);

 
ready
n.toString().length
function countDigits(n) {
  return n.toString().length;
}

countDigits(1);
countDigits(9);
countDigits(10);
countDigits(11);
countDigits(99);
countDigits(100);
countDigits(101);
countDigits(999);
countDigits(1000);
countDigits(1001);
countDigits(9999);
countDigits(10000);
countDigits(10001);
 
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.