integer length in javascript

40,029

Solution 1

Well, I don't think providing length properties to number will be helpful. The point is the length of strings does not change by changing its representation.

for example you can have a string similar to this:

var b = "sometext";

and its length property will not change unless you actually change the string itself.

But this is not the case with numbers.

Same number can have multiple representations. E.g.:

 var a = 23e-1;
and 
 var b = 2.3;

So its clear that same number can have multiple representations hence, if you have length property with numbers it will have to change with the representation of the number.

Solution 2

you must set variable toString() first, like this:

var num = 1024,
str = num.toString(),
len = str.length;

console.log(len);

Solution 3

You can find the 'length' of a number using Math.log10(number)

var num = 1024;
var len = Math.floor(Math.log10(num))+1;
console.log(len);

or if you want to be compatible with older browsers

var num = 1024;
var len = Math.log(num) * Math.LOG10E + 1 | 0; 
console.log(len);

The | 0 does the same this as Math.floor.

Share:
40,029
Ghoul Fool
Author by

Ghoul Fool

Ghoul fool is an artist. ...not a programmer He's really lost. #actuallyautistic

Updated on July 09, 2022

Comments

  • Ghoul Fool
    Ghoul Fool almost 2 years

    Stoopid question time!

    I know that in JavaScript you have to convert the integer to a string:

    var num = 1024;
    len = num.toString().length;
    console.log(len);
    

    My question is this: Why is there no get length property for integers in JavaScript? Is it something that isn't used that often?

  • Clergyman
    Clergyman over 10 years
    True, the integer value and hence length depends on the base of the number system.
  • Pimp Trizkit
    Pimp Trizkit over 6 years
    Maybe not very helpful. But, I could use it. While parsing a line of user text; I would use such a feature to tell me how much distance the parseInt function used from the source string. Without having to reconvert it back to string just to see. (ie: parsing x+2464+y*42)
  • Kerwin Sneijders
    Kerwin Sneijders about 2 years
    Do note that this results in: -Infinity when calling it with the number 0. Also returns NaN for negatives