Igor's Techno Club

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

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=10x. To find x, you can use the following formula:

d=log10(n)

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);
}

#java #math #productivity #til