Viktor Lindblad Viktor Lindblad - 1 year ago 74
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);
for(int i = 0; i < string.length(); i++) {
int j = Character.digit(string.charAt(i), 10);
this.number = new Number(j);
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 Source

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("#");
char[] d = df.format(v).toCharArray();
int count = 0;
for (int i = 0 ; i != d.length ; i++) {
    if (Character.isDigit(d[i])) {
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);


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download