gpt4 book ai didi

java - 如何将 String ArrayList 转换为 Double ArrayList 并计算值的总和?

转载 作者:行者123 更新时间:2023-11-29 06:56:09 25 4
gpt4 key购买 nike

我想做的是

  1. 获取我的字符串数组列表值并将它们添加到双数组列表。

  2. 计算double arraylist和中值的总和

  3. 将总和值设置为 TextView。


private ArrayList<String> totals = new ArrayList<>();
private ArrayList<Double> demototal = new ArrayList<>();
//Parsing the JSON String
try
{
total = itemData.getString(ParseBarcode.KEY_TOTAL);
}catch (JSONException e)
{
e.printStackTrace();
}
// add the parsed total to totals arraylist
totals.add(total);

//converting all values from totals array to Double and add to arraylist demototal
for (int i = 0; i < totals.size(); i++)
{
final String value = totals.get(i);
double total_ary = (double)Math.round((Double.parseDouble(value))*100.0)/100.0;
demototal.add(total_ary);

Toast.makeText(AddInvEst.this, total_ary+"", Toast.LENGTH_SHORT).show();
}

//converting double value to string for setting it to sum textView.
String amount = Double.toString(setArrayListElement(demototal));
textViewSum.setText(amount);//set total text to amount

//calculate amount here we pass setArrayListElement as Double arraylist
private Double setArrayListElement(ArrayList inArray) {
Double amount = 0.0d;
for (int i = 0; i < inArray.size(); i++) {
amount += Double.valueOf(Math.round((Double) inArray.get(i))*100.0)/100.0;
}
return amount;
}

My string arraylist contains values like [51,073,29,620] which is a currency value.

最佳答案

    List<String> stringList = new ArrayList<>();
stringList.add("1.2");
stringList.add("2.3");
stringList.add("3.4");
double result = stringList.stream().collect(Collectors.summingDouble(string -> Double.parseDouble(string)));

关于java - 如何将 String ArrayList 转换为 Double ArrayList 并计算值的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33717263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com