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:
To find X, you can use the following formula:
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