Java – How to count the number of digits in an int value?


Given the following code.

 int[] eg = {21,20,1,12,2}
 public numbers(int[] eg)
     for(int i=0; i < eg.length; i++)

I would expect eg.length to be 5, where eg[0] would = 21 eg[1] would = 20, eg[3] would = 1

I would like to check each element of eg[i] to see if it is a 1 digit or 2 digit number I tried eg[0].length to no avail, but am I correct in assuming that is only for Array Lists?

Best Solution

Convert the number to a String and get the length.

int length = String.valueOf(eg[i]).length();


int length = Integer.valueOf(eg[i]).toString().length();

Use this mathematical equation (assuming that all the data in the array are strictly positive numbers).

int length = (int)(Math.log10(eg[i])+1);