Convert a string into an array or list of floats

10,376

Solution 1

With rounding to 3 decimals...

    String[] parts = input.split("#");
    float[] numbers = new float[parts.length];
    for (int i = 0; i < parts.length; ++i) {
        float number = Float.parseFloat(parts[i]);
        float rounded = (int) Math.round(number * 1000) / 1000f;
        numbers[i] = rounded;
    }

Solution 2

Hope this helps...

String input = "0.1#5.338747#0.0";
String[] splittedValues = input.split("#");
List<Float> convertedValues = new ArrayList<Float>();
for (String value : splittedValues) {
    convertedValues.add(new BigDecimal(value).setScale(3, BigDecimal.ROUND_CEILING).floatValue());
}

Solution 3

String str = "0.1#0.2#0.3#0.4";
String[] results = str.split("#");
float fResult[] = new float[results.length()];
for(int i = 0; i < results.length(); i++) {
    fResult[i] = Float.parseFloat(String.format("%.3f",results[i]));
}

Solution 4

You can do it with guava:

final String str = "0.1#0.2#0.3#0.4";
final Iterable<Float> floats = Iterables.transform(Splitter.on("#").split(str), new Function<String, Float>() {
  public Float apply(final String src) {
    return Float.valueOf(src);
  }
});

or with the Java API:

final String str = "0.1#0.2#0.3#0.4";
final StringTokenizer strTokenizer = new StringTokenizer(str, "#");

final List<Float> floats = new ArrayList<Float>();
while (strTokenizer.hasMoreTokens()) {
    floats.add(Float.valueOf(strTokenizer.nextToken()));
}

Solution 5

On the account of getting 3 decimal places, try this:

public class Test {
    public static void main(String[] args) {
        String str = "0.12345#0.2#0.3#0.4";
        String[] results;
        results = str.split("#");
        float res1 = new Float(results[0]);
        System.out.println("res = " + res1);
        // cut to right accuracy
        res1 = ((int) (res1 * 1000)) / 1000f;
        System.out.println("res = " + res1);
    }
}
Share:
10,376
sambasam
Author by

sambasam

Updated on June 25, 2022

Comments

  • sambasam
    sambasam almost 2 years

    I have a string of fourteen values seperated by #

    0.1#5.338747#0.0#.... and so on

    I want to convert each value from a string to a float or double to 3 decimal places. I can do most of this the long way...

    str = "0.1#0.2#0.3#0.4";
    String[] results;
    results = str.split("#");
    float res1 = new Float(results[0]);
    

    but I'm not sure of the best way to get each float to 3 decimal places. I'd also prefer to do this in something neat like a for loop, but can't figure it out.