How to count digits of given number? JavaScript

The requirements here are simple, we are required to write a JavaScript function that takes in a number and returns the number of digits in it.

For example ?

The number of digits in 4567 is 4
The number of digits in 423467 is 6
The number of digits in 457 is 3

Let's explore different approaches to count digits in JavaScript.

Method 1: Using Recursive Approach

This method uses recursion to divide the number by 10 until it reaches zero:

const num = 2353454;
const digits = (num, count = 0) => {
    if(num){
        return digits(Math.floor(num / 10), ++count);
    };
    return count;
};
console.log(digits(num));
console.log(digits(123456));
console.log(digits(53453));
console.log(digits(5334534534));
7
6
5
10

Method 2: Using String Conversion

Convert the number to a string and count its length:

function countDigitsString(num) {
    return Math.abs(num).toString().length;
}

console.log(countDigitsString(4567));    // 4
console.log(countDigitsString(-423467)); // 6 (handles negative numbers)
console.log(countDigitsString(457));     // 3
console.log(countDigitsString(0));       // 1
4
6
3
1

Method 3: Using Logarithm

Use base-10 logarithm for mathematical calculation:

function countDigitsLog(num) {
    if (num === 0) return 1;
    return Math.floor(Math.log10(Math.abs(num))) + 1;
}

console.log(countDigitsLog(4567));    // 4
console.log(countDigitsLog(423467));  // 6
console.log(countDigitsLog(457));     // 3
console.log(countDigitsLog(1));       // 1
4
6
3
1

Comparison

Method Performance Handles Negative? Best For
Recursive Moderate No Educational purposes
String Conversion Fast Yes (with Math.abs) General use
Logarithm Fastest Yes (with Math.abs) Mathematical calculations

Handling Edge Cases

Here's a complete function that handles all edge cases:

function countDigits(num) {
    // Handle zero separately
    if (num === 0) return 1;
    
    // Convert to positive number and count digits
    return Math.abs(num).toString().length;
}

console.log(countDigits(0));        // 1
console.log(countDigits(-12345));   // 5
console.log(countDigits(9876543));  // 7
console.log(countDigits(-1));       // 1
1
5
7
1

Conclusion

The string conversion method is the most practical approach for counting digits, offering simplicity and good performance. Use the logarithm method for mathematical applications where precision and speed are critical.

Updated on: 2026-03-15T23:18:59+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements