Codementor Events

A quick way to find out how many digits are in a number

Published Apr 16, 2024
A quick way to find out how many digits are in a number

This is one of the many blog posts I have. See the full list on Igor's Techno Club

When you need to determine the number of digits in a number, the first approach that probably comes to my mind was always to convert it to a string first and then get the length of that string.

int numOfDigits = String.valueOf(number).length();

It works, but we can do better with a bit of math.

Consider the number 12,345 and its length; effectively, we are concerned about how many tens we have here, or how many times we need to multiply 10 to get the number 10,000. To put it in mathematical terms:

10000=10x10000 = 10^x

To find X, you can use the following formula:

d=log10(n)d = \left\lfloor \log_{10}(n) \right\rfloor

Since we interested in length of the number, and not in its logarithm value, we need to add to the result 1 count leading digit as well.

Putting everything together, you can use this approach:

public static int numDigits(int number) {
    if (number == 0) return 1;
    return (int) (Math.log10(Math.abs(number)) + 1);
}

Originally posted on Igorstechnoclub.com

Discover and read more posts from Igor Novokshonov
get started
post commentsBe the first to share your opinion
Show more replies