how to find numbers of digits in java

www‮.‬lautturi.com
how to find numbers of digits in java

To find the number of digits in an integer in Java, you can use a loop to divide the integer by 10 and count the number of iterations.

Here's an example of how to find the number of digits in an integer in Java:

int number = 12345;

int count = 0;

while (number > 0) {
  number /= 10;
  count++;
}

System.out.println("The number has " + count + " digits");

In the above example, a loop is used to divide the number variable by 10 and increment the count variable until the number variable becomes 0. At each iteration, the number variable is updated using the assignment operator (/=), which divides the variable by 10 and assigns the result back to the variable.

After the loop completes, the count variable will contain the number of digits in the number variable. This value is then printed to the console.

Keep in mind that this example only works for positive integers. If you need to handle negative integers or non-integer values, you may need to use a different approach. For example, you could use the String.length() method to find the number of digits in a string representation of the number.

For example:

double number = 12345.6789;

String str = String.valueOf(number);
int count = str.length();

System.out.println("The number has " + count + " digits");

In this example, the valueOf() method is used to convert the number variable to a string. The length() method is then used to get the length of the string, which is stored in the count variable. The count variable is then printed to the console.

Created Time:2017-11-01 20:42:52  Author:lautturi