我有一个由#
分隔的十四个值的字符串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循环一样整洁,但无法理解。
答案 0 :(得分:3)
舍入到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;
}
答案 1 :(得分: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]));
}
答案 2 :(得分:2)
您可以使用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);
}
});
或使用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()));
}
答案 3 :(得分: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());
}
答案 4 :(得分: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);
}
}