182

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?

Chad von Nau
  • 4,316
  • 1
  • 23
  • 34
bit4fox
  • 2,021
  • 2
  • 13
  • 8
  • 1
    12/2021 - Adding quotes to number like this `(number+'').length` will convert the content automatically to string, then you can use `.length`. – Mohamed Reda Dec 30 '21 at 10:35

20 Answers20

308

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
Community
  • 1
  • 1
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 3
    good technique to get no of digit, but, what if it is a fraction number, ie, 12.5, then your function will return 4 instead of 3... – Scarecrow Feb 14 '13 at 16:45
  • @Swarnendu: That's no problem because I have just integers. – bit4fox Feb 14 '13 at 16:47
  • 3
    Otherwise just use something like `number.toString().match(/\d/g).length`. – VisioN Mar 18 '14 at 10:08
  • 1
    @Bakudan - This answer appears to have been fixed. You can delete your two comments critiquing it now (so that future people don't get confused and think the code in this answer doesn't work.) – ArtOfWarfare May 28 '16 at 19:19
  • 1
    What is the purpose of `| 0`? I would assume it's some kind of implicit casting thing since anything `OR 0` is going to be itself but I would really appreciate an explanation. – 3ocene Apr 19 '17 at 17:33
  • 1
    @3ocene Good guess! The value stays the same but behind the scene it is casted to integer. `x | 0` is just another short and fast version of `Math.floor(x)`, which rounds down the number. You can achieve the same with `~~x`. The following question provides more explaination on the point: http://stackoverflow.com/q/9049677/1249581. – VisioN Apr 20 '17 at 07:15
  • Sixteen digit number 1,000Quadrillion would return 15.999999999999998 `(Math.log(Math.pow(10,15)||1)*Math.LOG10E)+1` – Nik Jul 18 '21 at 10:14
  • `1e22.toString().length` is 5! – cdalxndr Aug 15 '21 at 19:06
  • i found a problem `Math.log(99.99999999999999) * Math.LOG10E + 1 | 0;` here the answer should be 2 but returns 3 as if it's 100 not 99.999..... – Yasser CHENIK May 27 '22 at 12:41
  • @YasserCHENIK Check out the second (optimised) solution from [Mwr247](https://stackoverflow.com/a/28203456/1249581). It should handle such cases better. – VisioN May 27 '22 at 18:20
98

Here's a mathematical answer (also works for negative numbers):

function numDigits(x) {
  return Math.max(Math.floor(Math.log10(Math.abs(x))), 0) + 1;
}

And an optimized version of the above (more efficient bitwise operations): *

function numDigits(x) {
  return (Math.log10((x ^ (x >> 31)) - (x >> 31)) | 0) + 1;
}

Essentially, we start by getting the absolute value of the input to allow negatives values to work correctly. Then we run through the log10 operation to give us what power of 10 the input is (if you were working in another base, you would use the logarithm for that base), which is the number of digits. Then we floor the output to only grab the integer part of that. Finally, we use the max function to fix decimal values (any fractional value between 0 and 1 just returns 1, instead of a negative number), and add 1 to the final output to get the count.

The above assumes (based on your example input) that you wish to count the number of digits in integers (so 12345 = 5, and thus 12345.678 = 5 as well). If you would like to count the total number of digits in the value (so 12345.678 = 8), then add this before the 'return' in either function above:

x = Number(String(x).replace(/[^0-9]/g, ''));

* Please note that bitwise operations in JavaScript only work with 32-bit values (max of 2,147,483,647). So don't go using the bitwise version if you expect numbers larger than that, or it simply won't work.

Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
Mwr247
  • 1,300
  • 10
  • 16
  • 5
    Note: Math.log10 is ES6 function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log10 – Tx3 Sep 26 '15 at 11:27
  • 4
    @Tx3 Good note! Thankfully, `Math.LOG10E` has existed since ES1, which means `Math.log(x) * Math.LOG10E` will work for compatibility. – Mwr247 Sep 28 '15 at 14:53
  • I think this function does not work: ``` function numDigits(x) { return (Math.log10((x ^ (x >> 31)) - (x >> 31)) | 0) + 1; } ``` numDigits(1234567891) -> 10 numDigits(12345678912) -> 9 – lokhmakov Sep 12 '19 at 07:39
  • 2
    @lokhmakov That's because the second number you gave exceeds JavaScript's max 32-bit integer value, which bitwise operators (^, >>, |) can't handle correctly. – Mwr247 Sep 12 '19 at 08:08
  • The optimized version doesn't work for very large numbers, for example `console.log(numDigits(12345678901234567890) );`. Other one works fine though! – Justin May 19 '20 at 08:39
  • @Justin But of course, [because JS itself doesn't work for very large numbers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). The number you selected is larger than JS can safely operate on or even display correctly. This fact is certainly a benefit to the string based approaches of other answers over this one if the input is indeed large, but if you're passing something in as a workable number in JS this will work fine (though the optimized one should only work for 32-bit numbers, since bitwise operations are limited to those). – Mwr247 May 19 '20 at 13:28
  • 2
    True. One should expect that JS only works with the max safe int, and that number is much larger than almost anyone would need for anything. I'm developing a game with very large numbers and could not use the optimized code because of that limitation, and figured I'd comment to save anyone else in a similar boat from having broken code later down the line. Great answer by the way. – Justin May 20 '20 at 05:40
  • I created a mini little benchmark fiddle to test out the different techniques: https://jsfiddle.net/szc6ybe2/. Indeed, the optimized one is faster. – Ryan Wheale Jun 15 '20 at 19:16
  • When using the "optimized" function, I am incorrectly getting a result of 9 for 1593110999000. The first one works fine though. – Symphony0084 Aug 04 '20 at 04:03
  • @famouspotatoes See 2 comments above about max safe int. Data types have their size limits. – Mwr247 Aug 04 '20 at 07:00
  • @Mwr247 got it, thanks! didn't read all the comments before now – Symphony0084 Aug 04 '20 at 21:48
  • @cdalxndr See above comments about very large numbers and datatype maximums. I'll add it to the answer though since it seems to be a common question. – Mwr247 Aug 15 '21 at 22:25
  • "that number is much larger than almost anyone would need for anything" unix timestamp in milliseconds – Sam Nov 17 '21 at 03:30
23

Since this came up on a Google search for "javascript get number of digits", I wanted to throw it out there that there is a shorter alternative to this that relies on internal casting to be done for you:

var int_number = 254;
var int_length = (''+int_number).length;

var dec_number = 2.12;
var dec_length = (''+dec_number).length;

console.log(int_length, dec_length);

Yields

3 4
streetlogics
  • 4,640
  • 33
  • 33
9

it would be simple to get the length as

  `${NUM}`.length

where NUM is the number to get the length for

A P
  • 99
  • 1
  • 2
  • doesnt handle negative values (a minus would add an extra char), or decimal values (a comma would add an extra char). Also localization can add separators between groups of numbers (think 10'000). Its worth at least to mention this as a caveat to your answer. – Reinis Apr 12 '23 at 06:09
7

You can use in this trick:

(''+number).length
double-beep
  • 5,031
  • 17
  • 33
  • 41
Idan
  • 3,604
  • 1
  • 28
  • 33
3

var i = 1;
while( ( n /= 10 ) >= 1 ){ i++ }

23432          i = 1
 2343.2        i = 2
  234.32       i = 3
   23.432      i = 4
    2.3432     i = 5
    0.23432

user40521
  • 1,997
  • 20
  • 8
3

you can use the Math.abs function to turn negative numbers to positive and keep positives as it is. then you can convert the number to string and provide length.

Math.abs(num).toString().length;

i found this method the easiest and it works pretty good. but if you are sure you will be provided with positive number you can just turn it to string and then use length.

num.toString().length
DevAddict
  • 1,583
  • 1
  • 10
  • 17
2

If you need digits (after separator), you can simply split number and count length second part (after point).

function countDigits(number) {
    var sp = (number + '').split('.');
    if (sp[1] !== undefined) {
        return sp[1].length;
    } else {
        return 0;
    }
}
2

I'm still kind of learning Javascript but I came up with this function in C awhile ago, which uses math and a while loop rather than a string so I re-wrote it for Javascript. Maybe this could be done recursively somehow but I still haven't really grasped the concept :( This is the best I could come up with. I'm not sure how large of numbers it works with, it worked when I put in a hundred digits.

function count_digits(n) {
    numDigits = 0;
    integers = Math.abs(n);

    while (integers > 0) {
        integers = (integers - integers % 10) / 10;
        numDigits++;
    }
    return numDigits;
}

edit: only works with integer values

Nate
  • 21
  • 2
2

Note : This function will ignore the numbers after the decimal mean dot, If you wanna count with decimal then remove the Math.floor(). Direct to the point check this out!

function digitCount ( num )
{
     return Math.floor( num.toString()).length;
}

 digitCount(2343) ;

// ES5+

 const digitCount2 = num => String( Math.floor( Math.abs(num) ) ).length;

 console.log(digitCount2(3343))

Basically What's going on here. toString() and String() same build-in function for converting digit to string, once we converted then we'll find the length of the string by build-in function length.

Alert: But this function wouldn't work properly for negative number, if you're trying to play with negative number then check this answer Or simple put Math.abs() in it;

Cheer You!

Ericgit
  • 6,089
  • 2
  • 42
  • 53
1

Problem statement: Count number/string not using string.length() jsfunction. Solution: we could do this through the Forloop. e.g

for (x=0; y>=1 ; y=y/=10){
  x++;
}

if (x <= 10) {
  this.y = this.number;                
}   

else{
  this.number = this.y;
}    

}

Yogesh Aggarwal
  • 994
  • 7
  • 9
1
`You can do it by simple loop using Math.trunc() function. if in interview interviewer ask to do it without converting it into string`
    let num = 555194154234 ;
    let len = 0 ;
    const numLen = (num) => {
     for(let i = 0; i < num ||  num == 1 ; i++){
        num = Math.trunc(num/10);
        len++ ;
     }
      return len + 1 ;
    }
    console.log(numLen(num));
1

Please use the following expression to get the length of the number.

length = variableName.toString().length
mechnicov
  • 12,025
  • 4
  • 33
  • 56
1

While not technically answering this question, if you're looking for the length of the fractional part of a number (e.g. 1.35 => 2 or 1 => 0), this may help you:

function fractionalDigitLength(num) {
  if (Number.isInteger(num)) return 0;
  return String(num).split('.')[1].length;
}

Note: Reason I'm posting here as I think people googling this answer may also want a solution to just getting the fractional length of a number.

Dana Woodman
  • 4,148
  • 1
  • 38
  • 35
0

Two digits: simple function in case you need two or more digits of a number with ECMAScript 6 (ES6):

const zeroDigit = num => num.toString().length === 1 ? `0${num}` : num;
0

Here is my solution. It works with positive and negative numbers. Hope this helps

function findDigitAmount(num) {

   var positiveNumber = Math.sign(num) * num;
   var lengthNumber = positiveNumber.toString();

 return lengthNumber.length;
}


(findDigitAmount(-96456431);    // 8
(findDigitAmount(1524):         // 4
0

A solution that also works with both negative numbers and floats, and doesn't call any expensive String manipulation functions:

function getDigits(n) {
   var a = Math.abs(n);            // take care of the sign
   var b = a << 0;                 // truncate the number
   if(b - a !== 0) {               // if the number is a float
       return ("" + a).length - 1; // return the amount of digits & account for the dot
   } else {
       return ("" + a).length;     // return the amount of digits
   }
}
Caltrop
  • 895
  • 1
  • 7
  • 20
0

for interger digit we can also implement continuously dividing by 10 :

var getNumberOfDigits = function(num){
    var count = 1;
    while(Math.floor(num/10) >= 1){
        num = Math.floor(num/10);
        ++count;
    }
    return count;
}

console.log(getNumberOfDigits(1))
console.log(getNumberOfDigits(12))
console.log(getNumberOfDigits(123))
ganesh phirke
  • 471
  • 1
  • 3
  • 12
0

heres a correct mathematical answer (using logarithms) that is also well explained:

function numberOfDigitsInIntegerPart(numberToGetDigitsFor: number): number {
    const valueWithoutNegative = Math.abs(numberToGetDigitsFor);

    if (valueWithoutNegative === 0) {
        // Math.log10(0) === -Infinity
        return 1;
    }

    if (valueWithoutNegative > 0 && valueWithoutNegative < 1) {
        // Math.log10(0.1) === -1
        // Math.log10(0.2) === -0.6989700043360187
        // etc
        return 1;
    }

    if (valueWithoutNegative === 1) {
        // Math.log10(1) === 0
        return 1;
    }

    // Math.log10(1.1) === 0.04139268515822507
    // Math.log10(2000) === 3.3010299956639813
    // Math.log10(10000) ==== 4
    // etc

    const powerToWhich10MustBeExponentiatedToGetValue = Math.log10(valueWithoutNegative);
    const closestRoundPowerBelowExponentationToGetValue = Math.floor(powerToWhich10MustBeExponentiatedToGetValue);

    return closestRoundPowerBelowExponentationToGetValue + 1;
}

Logarithms, for those, who've forgotten highschool maths classes (I know I had before writing this answer) are the opposites of power. Math.log10(x) is asking "to what power do I need to multiply 10 to get x"?

So

Math.log10(100) will be 2, because 10^2 (10x10) is 100,

Math.log10(1000) will be 3, because 10^3 (10x10x10) is 1000

etc

Reinis
  • 132
  • 2
  • 16
-7

The length property returns the length of a string (number of characters).

The length of an empty string is 0.

var str = "Hello World!";
var n = str.length;

The result of n will be: 12

    var str = "";
    var n = str.length;

The result of n will be: 0


Array length Property:


The length property sets or returns the number of elements in an array.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;

The result will be: 4

Syntax:

Return the length of an array:

array.length

Set the length of an array:

array.length=number
Muhammad Awais
  • 4,238
  • 1
  • 42
  • 37