Java Program to Count Number of Digits in a Number
To count the number of digits in a Java integer, you can repeatedly divide the number by 10, convert the number to a String and use length(), or calculate the digit count mathematically. The division method is useful when you want to work directly with the numeric value.
For example, the number 5698234 contains 7 digits. With integer division, every division by 10 removes the last decimal digit: 5698234 becomes 569823, then 56982, and so on until the value becomes 0. Counting these divisions gives the number of digits.
Count Digits in a Java Integer Using a while Loop
In this example, we shall take a number initialized to an integer variable num, and initialize the count to zero.
The while loop runs while num != 0. During every iteration, integer division by 10 removes the last digit and count is incremented by one.
Because the loop executes once for each digit in num, the final value of count is the number of digits in the original number.
Example.java
/**
* Java Program - Count Number of Digits in Integer
*/
public class Example {
public static void main(String[] args) {
//number
int num = 5698234;
//variable to store count of digits in number
int count = 0;
//count number of digits in num
while(num!=0) {
num = num/10; //removes last digit of num
count++;
}
//print the count
System.out.println(count);
}
}
Run the above Java program. You shall get the following output in console output.
Output
7
How the while Loop Counts the Seven Digits
Following snippet shows the values of num and count variables during each iteration of the while loop.
num : 5698234
count : 0
Iteration : 1
While condition (num!=0) 5698234!=0 is true
num : 569823
count : 1
Iteration : 2
While condition (num!=0) 569823!=0 is true
num : 56982
count : 2
Iteration : 3
While condition (num!=0) 56982!=0 is true
num : 5698
count : 3
Iteration : 4
While condition (num!=0) 5698!=0 is true
num : 569
count : 4
Iteration : 5
While condition (num!=0) 569!=0 is true
num : 56
count : 5
Iteration : 6
While condition (num!=0) 56!=0 is true
num : 5
count : 6
Iteration : 7
While condition (num!=0) 5!=0 is true
num : 0
count : 7
Iteration : 8
While condition (num!=0) 0!=0 is false
count : 7
After seven divisions, num becomes 0, so the loop stops and count is 7.
Count Digits Correctly for Zero and Negative Numbers in Java
The basic loop above works for positive, non-zero integers, but two edge cases deserve attention. The number 0 has one digit, yet a loop whose condition is num != 0 would execute zero times. Negative numbers should also be counted without treating the minus sign as a digit.
A practical implementation can handle both cases by returning 1 for zero and performing the calculation on the absolute value of the number. Converting the int to long before applying Math.abs() also handles Integer.MIN_VALUE safely.
public class Example {
public static void main(String[] args) {
int num = -5698234;
long value = Math.abs((long) num);
int count = 0;
if (value == 0) {
count = 1;
} else {
while (value != 0) {
value /= 10;
count++;
}
}
System.out.println(count);
}
}
The minus sign in -5698234 is not a digit, so this program prints 7.
7
Count Digits in a Number Using String.length() in Java
Another approach is to convert the integer to a string and use String.length(). For a positive integer, the number of characters in its decimal representation is the same as its number of digits.
In the following existing example, appending an empty string with num+"" produces a string representation of num. Calling (num+"").length() then returns its length.
Example.java
/**
* Java Program - Count Number of Digits in Integer
*/
public class Example {
public static void main(String[] args) {
//number
int num = 5698234;
//convert number to string and find the length
int count = (num+"").length();
//print the count
System.out.println(count);
}
}
Run the above Java program, and you shall get the following output.
Output
7
Using String.valueOf() When the Number May Be Negative
For a negative integer, converting the number directly to a string includes the - sign. For example, String.valueOf(-1234).length() is 5, even though the number itself contains only four digits. Take the absolute value before converting it to a string when only digits should be counted.
int num = -1234;
int count = String.valueOf(Math.abs((long) num)).length();
System.out.println(count);
4
Java Digit Count Formula Using Math.log10()
For a positive integer n, the number of decimal digits can also be calculated with floor(log10(n)) + 1. In Java, this can be written using Math.log10().
int count = (int) Math.floor(Math.log10(number)) + 1;
The formula requires special handling for 0, because Math.log10(0) does not produce a finite digit-count value. Negative numbers should first be converted to their absolute value.
public class Example {
public static void main(String[] args) {
int num = 5698234;
long value = Math.abs((long) num);
int count = value == 0
? 1
: (int) Math.floor(Math.log10(value)) + 1;
System.out.println(count);
}
}
7
while Loop vs String.length() vs Math.log10() for Digit Counting
Each approach gives the same result for ordinary positive integers, but they solve the problem differently:
- Repeated division by 10: works directly with the numeric value and clearly demonstrates how decimal digits are removed one at a time.
- String.length(): is concise and easy to read, but a negative sign must not be included in the digit count.
- Math.log10(): expresses the mathematical digit-count formula compactly, but zero requires a separate case.
For a beginner-level Java program, repeated division is usually the clearest method because the relationship between the loop iterations and the digits can be observed directly.
Java Digit-Count Cases to Verify
When checking a program that counts digits, test values that cover the important numeric cases:
7should have1digit.5698234should have7digits.0should have1digit.-1234should have4digits; the minus sign is not a digit.1000should have4digits, including the three trailing zeroes.Integer.MIN_VALUEshould be handled without overflowing when its absolute value is needed; converting tolongfirst avoids that problem.
What to Remember When Counting Digits in Java
Dividing an integer by 10 removes its last decimal digit, so the number of divisions required to reach zero is the number of digits. A string-based solution can obtain the same result with length(), while Math.log10() provides a mathematical alternative. Whichever approach you use, handle 0 as a one-digit number and do not count a negative sign as a digit.
In this Java Tutorial, we learned how to count the number of digits in a given number.
TutorialKart.com