3

我有一串由 # 分隔的十四个值

0.1#5.338747#0.0#....等等

我想将每个值从字符串转换为浮点数或将双精度值转换为小数点后 3 位。我可以在很长的时间内完成大部分工作......

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

但我不确定将每个浮点数精确到小数点后 3 位的最佳方法。我也更喜欢在 for 循环之类的简洁的东西中执行此操作,但无法弄清楚。

4

5 回答 5

4

四舍五入到小数点后三位...

    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;
    }
于 2012-04-24T09:40:53.870 回答
2
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]));
}
于 2012-04-24T09:37:20.060 回答
2

你可以用番石榴做到这一点:

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

或使用 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()));
}
于 2012-04-24T09:38:37.720 回答
2

希望这可以帮助...

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());
}
于 2012-04-24T09:43:49.933 回答
1

考虑到小数点后 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);
    }
}
于 2012-04-24T09:43:01.193 回答