Get number of digits using JavaScript

As the name of my post shows, I would like to know how many digits a var number . 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 that it does not work due to TypeError :

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

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

+97
javascript count digits
Feb 14 '13 at 16:39
source share
9 answers

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 positive integers 

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; // for floats 
+193
Feb 14 '13 at 16:39
source share

Here's the math answer (also works for negative numbers):

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

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

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

Essentially, we start by getting an absolute input value to allow negative values ​​to work correctly. Then we run the operation log10 to give us that the input power is 10 (if you are working on another base, you should use the logarithm for this base), that is, the number of digits. We then infer the output to get only the whole part of it. Finally, we use the max function to fix the decimal values ​​(any fractional value between 0 and 1 just returns 1 instead of a negative number) and adds 1 to the final result to get the score.

The above assumes (based on your input example) that you want to count the number of digits in integers (so 12345 = 5 and therefore 12345.678 = 5). If you want to calculate the total number of digits in a value (so 12345.678 = 8), add this before “returning” to any of the functions listed above:

 x = Number(String(x).replace(/[^0-9]/g, '')); 
+57
Jan 28 '15 at 10:14
source share

Since this led to a Google search for “javascript to get the number of digits”, I would like to drop it there, that there is a shorter alternative to this that relies on the 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); 

Productivity

 3 4 
+19
May 01 '14 at 21:17
source share

If you need numbers (after the separator), you can simply divide the number and length of the second part (after the period).

 function countDigits(number) { var sp = (number + '').split('.'); if (sp[1] !== undefined) { return sp[1].length; } else { return 0; } } 
+2
Oct 12 '15 at 7:59
source share

I'm still learning Javascript, but I came up with this function in C some time ago that uses the math and while loop, rather than a string, so I rewrote it for Javascript. Maybe it can be done recursively in some way, but I still do not understand this concept: (This is the best I could come up with. I'm not sure how many numbers it works with, it worked when I put a hundred numbers.

 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

+1
Nov 04 '15 at 17:35
source share

 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 

+1
May 22 '16 at 12:01
source share

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

 const zeroDigit = num => num.toString().length === 1 ? '0${num}' : num; 
0
Jun 05 '18 at 10:17
source share

Problem statement: read a number / string without using jsfunction string.length () . Solution: we could do it through Forloop. eg

 for (x=0; y>=1 ; y=y/=10){ x++; } if (x <= 10) { this.y = this.number; } else{ this.number = this.y; } 

}

0
Aug 17 '18 at 10:00
source share

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

The length of the empty string is 0.

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

Result n will be: 12

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

Result n will be: 0




Array Length Property:




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

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

The result will be: 4

Syntax:

Returns the length of the array:

 array.length 

Set the length of the array:

 array.length=number 
-5
Jun 02 '16 at 6:23
source share



All Articles