Get number of digits with JavaScript

bit4fox picture bit4fox · Feb 14, 2013 · Viewed 203.7k times · Source

As the title of my post suggests, I would like to know how many digits var number has. For example: If number = 15; my function should return 2. Currently, it looks like this:

function getlength(number) {
  return number.toString().length();
}

But Safari says it is not working due to a TypeError:

'2' is not a function (evaluating 'number.toString().length()')

As you can see, '2' is actually the right solution. But why is it not a function?

Answer

VisioN picture VisioN · Feb 14, 2013

length is a property, not a method. You can't call it, hence you don't need parenthesis ():

function getlength(number) {
    return number.toString().length;
}

UPDATE: As discussed in the comments, the above example won't work for float numbers. To make it working we can either get rid of a period with String(number).replace('.', '').length, or count the digits with regular expression: String(number).match(/\d/g).length.

In terms of speed potentially the fastest way to get number of digits in the given number is to do it mathematically. For positive integers there is a wonderful algorithm with log10:

var length = Math.log(number) * Math.LOG10E + 1 | 0;  // for positive integers

For all types of integers (including negatives) there is a brilliant optimised solution from @Mwr247, but be careful with using Math.log10, as it is not supported by many legacy browsers. So replacing Math.log10(x) with Math.log(x) * Math.LOG10E will solve the compatibility problem.

Creating fast mathematical solutions for decimal numbers won't be easy due to well known behaviour of floating point math, so cast-to-string approach will be more easy and fool proof. As mentioned by @streetlogics fast casting can be done with simple number to string concatenation, leading the replace solution to be transformed to:

var length = (number + '').replace('.', '').length;  // for floats