At times, you might be required to count the number of digits in our given number. If we were to do it manually, it would be a very easy task, but when it comes to programming, it may be a little bit tricky. So, in this article, we are going to write a simple Java program, in which, we are going to count the number of digits in the given number. For example, if the given number is 12345, then the number of digits is 5.
How to Count Number of Digits in Java
To count the total number of digits, we just need to iterate through the number, count one digit from the end, remove it, and continue this, till it becomes zero.
In the given video, you can find an easy explanation along with a program to count the number of digits in Java.
Here is the Java program to count the number of digits from the given number –
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
long number = scanner.nextLong();
// Handle negative numbers by making them positive
if (number < 0) {
number = -number;
}
// Initialize a counter for digits
int count = 0;
// Special case for the number 0
if (number == 0) {
count = 1;
} else {
// Count digits using a loop
while (number > 0) {
number /= 10;
count++;
}
}
System.out.println("Number of digits: " + count);
scanner.close();
}
}
Program Output 1 –
Enter an integer: 12345
Number of digits: 5
Program output 2 –
Enter an integer: -12625
Number of digits: 5