length is a property, not a method. You cannot call it, so you do not need a bracket () :
function getlength(number) { return number.toString().length; }
UPDATE:. As discussed in the comments, the above example will not work for floating point numbers. To make it work, we can either get rid of the period with String(number).replace('.', '').length , or count the numbers with a regular expression: String(number).match(/\d/g).length .
In terms of speed, the potentially fastest way to get the number of digits in a 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 all types of integers (including negatives) there is a brilliant optimized solution from @ Mwr247 , but be careful using Math.log10 as it is not supported by many older browsers. Therefore, replacing Math.log10(x) with Math.log(x) * Math.LOG10E will solve the compatibility problem.
Creating quick math solutions for decimal numbers will not be easy due to the well-known behavior of floating point math , so a string-based approach will be simpler and proof of a fool. As @streetlogics mentioned, fast execution can be performed with a prime until the string is concatenated, which leads to replacing the solution that needs to be converted to:
var length = (number + '').replace('.', '').length;
VisioN Feb 14 '13 at 16:39 2013-02-14 16:39
source share