[javascript] Get number of digits with JavaScript

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?

This question is related to javascript count digits

The answer is


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

it would be simple to get the length as

  `${NUM}`.length

where NUM is the number to get the length for


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

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!


You can use in this trick:

(''+number).length

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


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


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

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

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

}


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. look at this function:

const digitCount = num => Math.abs(num).toString().length;

i found this method the easiest and it works pretty good.


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

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, ''));

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;

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

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


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

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

length = variableName.toString().length

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to count

Count the Number of Tables in a SQL Server Database SQL count rows in a table How to count the occurrence of certain item in an ndarray? Laravel Eloquent - distinct() and count() not working properly together How to count items in JSON data Powershell: count members of a AD group How to count how many values per level in a given factor? Count number of rows by group using dplyr C++ - how to find the length of an integer JPA COUNT with composite primary key query not working

Examples related to digits

C++ - how to find the length of an integer Gets last digit of a number Sum the digits of a number Get number of digits with JavaScript How do I separate an integer into separate digits in an array in JavaScript? C: how to break apart a multi digit number into separate variables? Show a leading zero if a number is less than 10 How to tell if string starts with a number with Python? in python how do I convert a single digit number into a double digits string? Controlling number of decimal digits in print output in R