Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer length in javascript

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?

like image 218
Ghoul Fool Avatar asked Aug 09 '13 08:08

Ghoul Fool


People also ask

Can you use length on an integer JavaScript?

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.

How do you find the length of a number in JavaScript?

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.

How big is an integer in JavaScript?

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.

What is the length of INT?

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.


1 Answers

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.

like image 110
Frazer Kirkman Avatar answered Oct 07 '22 01:10

Frazer Kirkman