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 there to eg.length
be 5, where eg[0]
would be = 21 eg[1]
would be = 20, eg[3]
would be = 1
I would like to check each element, eg [i] to see if it is a 1-digit or 2-digit number, which I tried to eg[0].length
no avail, but can I assume this is only for lists of arrays?
source to share
eg[i]
is of a type int
that has no property length
.
There are many ways to find out how many digits a number has:
-
write your own method that accepts
int
and continues to divide by 10 until the number reaches 0. -
using math properties:
int length = (int) (Math.log10(number) + 1);
-
converting a number to a String and using its methods
source to share
There is an algorithm used in the JDK that is probably the fastest:
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
// Requires positive x
static int stringSize(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}
source to share
If you want to see what the length of the number is, MChaker's solution is correct. However, if you want to know if a number contains a digit or a digit more than one digit, you can consider the following solution:
public class NumberTest {
public static void main(String[] args) {
int[] eg = {21,20,1,12,2, -3, -8, -20};
System.out.println("Array Length: " + eg.length);
for(int i=0; i < eg.length; i++) {
System.out.println("#" + i + ": Value: " + eg[i] + " one digit number: " + isOneDigitNumber(eg[i]));
}
}
static private boolean isOneDigitNumber(int number) {
return (-10 < number && number < 10);
}
}
and here is the result of the above code:
Array Length: 8
#0: Value: 21 one digit number: false
#1: Value: 20 one digit number: false
#2: Value: 1 one digit number: true
#3: Value: 12 one digit number: false
#4: Value: 2 one digit number: true
#5: Value: -3 one digit number: true
#6: Value: -8 one digit number: true
#7: Value: -20 one digit number: false
#7: Value: -20 one digit number: false
source to share