integer length in javascript
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.
Ghoul Fool
Ghoul fool is an artist. ...not a programmer He's really lost. #actuallyautistic
Updated on July 09, 2022Comments
-
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 over 10 yearsTrue, the integer value and hence length depends on the base of the number system.
-
Pimp Trizkit over 6 yearsMaybe 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: parsingx+2464+y*42
) -
Kerwin Sneijders about 2 yearsDo note that this results in:
-Infinity
when calling it with the number0
. Also returnsNaN
for negatives