简体   繁体   English

将字符串转换为数组或浮点数列表

[英]Convert a string into an array or list of floats

I have a string of fourteen values seperated by # 我有一串由14个值分隔的字符串#

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

I want to convert each value from a string to a float or double to 3 decimal places. 我想将每个值从字符串转换为浮点数或双倍转换为3位小数。 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. 但我不确定将每个浮点数移到3位小数的最佳方法。 I'd also prefer to do this in something neat like a for loop, but can't figure it out. 我也更喜欢像for循环一样整洁,但无法理解。

With rounding to 3 decimals... 舍入到3位小数...

    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;
    }
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]));
}

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: 或者使用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()));
}

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());
}

On the account of getting 3 decimal places, try this: 在获得3位小数的帐户上,试试这个:

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM