Viktor Lindblad Viktor Lindblad - 3 months ago 8
Java Question

How to go through a number (float) and get every number seperately with an int. Java

Is there any good way to search through a floats first four numbers and return every number seperately with int[]?

Example: the float 23,51 becomes the integer array, array[0]=2, array[1]=3, array[2]=5 and last arra[3]=1

My code:

public void printNumber(float number){
String string = String.valueOf(number);
while(!numbers.isEmpty()){
numbers.remove(0);
}
for(int i = 0; i < string.length(); i++) {
int j = Character.digit(string.charAt(i), 10);
this.number = new Number(j);
numbers.add(this.number);
System.out.println("digit: " + j);
}
}


I should mention that Number is a class that only returns a different picture based on the number the constructor is given and ofcourse the number itself.

numbers is an ArrayList

Answer

Convert float to String using fixed-point format, then go through its characters one-by-one, and ignore the decimal point.

If the number could also be negative, you need to pay attention to the sign in the String output:

float v = 23.51F;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(8);
char[] d = df.format(v).toCharArray();
int count = 0;
for (int i = 0 ; i != d.length ; i++) {
    if (Character.isDigit(d[i])) {
        count++;
    }
}
int[] res = new int[count];
int pos = 0;
for (int i = 0 ; i != d.length ; i++) {
    if (Character.isDigit(d[i])) {
        res[pos++] = Character.digit(d[i], 10);
    }
}

Demo.

Important: Be aware that floats are inherently imprecise, so you may get a "stray" digit or two. For example, your example produces

[2 3 5 1 0 0 0 0 2 3]

with 2 and 3 at the end.