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?
Integers have standard data type length, so there's no need to calculate their 'length'. If you are referring to string representation length of int - it's obvious that you should first convert it to string.
To get the length of a number, call the toString() method on the number to convert it to a string, then access the length property of the string, i.e., num. toString(). length . We call the toString() method on the number to get its string representation.
Description. The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991, or ~9 quadrillion). Double precision floating point format only has 52 bits to represent the mantissa, so it can only safely represent integers between -(253 – 1) and 253 – 1.
The length of an integer field is defined in terms of number of digits; it can be 3, 5, 10, or 20 digits long. A 3-digit field takes up 1 byte of storage; a 5-digit field takes up 2 bytes of storage; a 10-digit field takes up 4 bytes; a 20-digit field takes up 8 bytes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With