Get number of digits with JavaScript

JavascriptCountDigits

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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 the 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 (so a 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.

Solution 3 - Javascript

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

Solution 4 - Javascript

it would be simple to get the length as

  `${NUM}`.length

where NUM is the number to get the length for

Solution 5 - Javascript

You can use in this trick:

(''+number).length

Solution 6 - Javascript

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;
    }
}

Solution 7 - Javascript

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

Solution 8 - Javascript

>

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

>

Solution 9 - Javascript

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!

Solution 10 - Javascript

`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));

Solution 11 - Javascript

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

length = variableName.toString().length

Solution 12 - Javascript

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.

Solution 13 - Javascript

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;

Solution 14 - Javascript

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;
}    

}

Solution 15 - Javascript

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

Solution 16 - Javascript

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
   }
}

Solution 17 - Javascript

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))

Solution 18 - Javascript

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

Solution 19 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionbit4foxView Question on Stackoverflow
Solution 1 - JavascriptVisioNView Answer on Stackoverflow
Solution 2 - JavascriptMwr247View Answer on Stackoverflow
Solution 3 - JavascriptstreetlogicsView Answer on Stackoverflow
Solution 4 - JavascriptA PView Answer on Stackoverflow
Solution 5 - JavascriptIdanView Answer on Stackoverflow
Solution 6 - JavascriptMaciej MaciejView Answer on Stackoverflow
Solution 7 - JavascriptNateView Answer on Stackoverflow
Solution 8 - Javascriptuser40521View Answer on Stackoverflow
Solution 9 - JavascriptEricgitView Answer on Stackoverflow
Solution 10 - JavascriptRajat SrivastavaView Answer on Stackoverflow
Solution 11 - JavascriptPriya ShaliniView Answer on Stackoverflow
Solution 12 - JavascriptDana WoodmanView Answer on Stackoverflow
Solution 13 - JavascriptRafael MelónView Answer on Stackoverflow
Solution 14 - JavascriptYogesh AggarwalView Answer on Stackoverflow
Solution 15 - JavascriptJuliana MeloView Answer on Stackoverflow
Solution 16 - JavascriptCaltropView Answer on Stackoverflow
Solution 17 - Javascriptganesh phirkeView Answer on Stackoverflow
Solution 18 - JavascriptDevAddictView Answer on Stackoverflow
Solution 19 - JavascriptMuhammad AwaisView Answer on Stackoverflow