Way to get number of digits in an int?
To get the number of digits in an int in Java, you can use the log10() method of the Math class and then add 1 to the result.
To get the number of digits in a positive int in Java, you can use the log10() method of the Math class and then add 1 to the result. This will give you the number of digits in the integer.
Here's an example of how to use log10() to get the number of digits in an int:
public class Main {
public static void main(String[] args) {
int num = 12345;
int digits = (int) Math.log10(num) + 1;
System.out.println("Number of digits: " + digits); // Outputs: "Number of digits: 5"
}
}Note that the log10() method returns the base-10 logarithm of the number. Casting the result to int truncates the decimal part, so adding 1 gives the actual number of digits for positive values.
You can also use the String.length() method to get the number of digits in an int, like this:
public class Main {
public static void main(String[] args) {
int num = 12345;
String str = String.valueOf(num);
int digits = str.length();
System.out.println("Number of digits: " + digits); // Outputs: "Number of digits: 5"
}
}This will convert the int to a string and then use the length() method to get the number of characters in the string, which is equivalent to the number of digits in the integer.
Handling zero and negative values
Both methods above assume positive integers. Math.log10() returns -Infinity for 0 and NaN for negative numbers. For negative numbers, String.valueOf() includes the minus sign, so the length will be one greater than the digit count. To handle zero and negative values correctly, you can use:
int digits = (num == 0) ? 1 : (int) Math.log10(Math.abs(num)) + 1;
// or
int digits = String.valueOf(Math.abs(num)).length();Performance note
The Math.log10() approach is generally faster and uses less memory since it avoids string allocation, making it preferable for performance-critical loops. The string conversion approach is more readable and often preferred for general-purpose code.