3

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

Example: the float 23,51 becomes the integer array, array[0]=2, array[1]=3, array[2]=5 and last array[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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Viktor Lindblad
  • 100
  • 1
  • 9

5 Answers5

5

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Tip: To avoid the mentioned inaccuracy of `float` introducing extraneous extra digits at the end, use [`BigDecimal`](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html) objects to represent fractional numbers instead of `float` and `double` primitives. – Basil Bourque Aug 30 '16 at 19:44
  • @BasilBourque Absolutely, `BigDecimal` would solve this problem. However, one needs to have `BigDecimal` to begin with. If you construct it from a `float` or `double`, the problem is back; if you start with a `String`, you can skip `BigDecimal` altogether. – Sergey Kalinichenko Aug 30 '16 at 19:47
1

You can convert the float to String with 4 decimal places using String.format method, and then get each character to int array

float floatValue = 12.34567f;
String str = String.format("%.4f", floatValue);
// remove the minus, dot, or comma (used in some countries)
str = str.replaceAll("[-|.|,]", "");
int [] nums  = new int[str.length()];
for (int i=0; i<str.length(); i++) {
  nums [i] = str.charAt(i) - '0';
}

Here is DEMO

As for the code last line, decimal value of '0' char (which is 48) is subtracted from a decimal value of digit char, and the result is integer value of that digit (as specified in below table):
enter image description here

MaxZoom
  • 7,619
  • 5
  • 28
  • 44
1

Java 8 flavored solution:

float number = -7.54f;
int[] digits = String.format("%.3f", number)
                     .chars()
                     .filter(Character::isDigit)
                     .limit(4L)
                     .map(Character::getNumericValue)
                     .toArray();

System.out.println(Arrays.toString(digits)); //=> [7, 5, 4, 0]
beatngu13
  • 7,201
  • 6
  • 37
  • 66
0

Use the static method Float.toString() to convert your float to a String.

Then go through each char and use Integer.parseInt() to get back to an int.

public void printNumber(float number){
    String string = Float.toString(number);

    for(int i = 0; i < string.length(); i++) {
        int j = Integer.parseInt(string.charAt(i));
        this.number = new Number(j);
        numbers.add(this.number);
        System.out.println("digit: " + j);
    }
}
element11
  • 4,218
  • 2
  • 16
  • 22
0

Another option

public static void main(String[] args) {

   float number = 23.51f;
   String strNumber = String.valueOf(number).replaceAll("\\D", "");
   int[] arrNumber = new int[strNumber.length()];

   for (int pos = 0; pos < strNumber.length(); ++pos) {
        arrNumber[pos] = Integer.valueOf(String.valueOf(strNumber.charAt(pos)));
        System.out.println(arrNumber[pos]);
    }
}
tnas
  • 510
  • 5
  • 16