How to Get the Length of an Integer in JavaScript?

You can get the number of digits in a JavaScript number in the following ways:

If the number you wish to calculate the length for is very large (e.g. Number.MAX_VALUE), then you should consider converting the number to bigint first.

Converting to String and Checking the length

You can simply convert the number to a string and access the length property on it to find the total number of digits in the number:

// ES6+
const numLen = (num) => String(Math.abs(num)).length;

console.log(numLen(0)); // 1
console.log(numLen(-0)); // 1
console.log(numLen(-12345)); // 5
console.log(numLen(12345)); // 5

For versions earlier than ES6, you can use the traditional function syntax instead of an arrow function (as arrow function was introduced in ES6).

Math.abs() is needed so that the minus symbol is removed from a negative number prior to converting the number to a string. Otherwise, the minus symbol (-) will be converted to string as is and will be counted in the string length.

Calculating the Number of Digits

You can calculate the number of digits in a number in the following way:

// ES6+
const numLen = (num) => (num === 0)
    ? 1
    : Math.ceil(Math.log10(Math.abs(num) + 1))
;

console.log(numLen(0)); // 1
console.log(numLen(-0)); // 1
console.log(numLen(12345)); // 5
console.log(numLen(-12345)); // 5

The check for 0 is necessary as log10(0) is equal to -Infinity.

Math.log10 was added in ES6; for versions prior to that, you could do the following:

function numLen(num) {
    if (num === 0) {
        return 1;
    }

    return Math.ceil(Math.log(Math.abs(num) + 1) / Math.LN10);
}

console.log(numLen(0)); // 1
console.log(numLen(-0)); // 1
console.log(numLen(12345)); // 5
console.log(numLen(-12345)); // 5

Looping and Removing Digits Off the End

You can simply create a loop, and remove the last digit from the number in each iteration till there are no digits left. In each iteration you can increment a counter, which would give you the total number of digits in the number:

function numLen(num) {
    let len = 0;

    do {
        // take last digit off `num`
        num = parseInt(num / 10, 10);
        // increment counter
        len++;
    } while (num !== 0);

    return len;
}

console.log(numLen(0)); // 1
console.log(numLen(-0)); // 1
console.log(numLen(-12345)); // 5
console.log(numLen(12345)); // 5

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.