java 从 BigDecimal [ ] 添加值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12556400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
adding values from a BigDecimal [ ]
提问by Sheeyla
I am struggling in finding a way to add up the values from a BigDecimal [ ] , which is obtained from a checkbox form out of a table from mysql.
我正在努力寻找一种将 BigDecimal [] 中的值相加的方法,该值是从 mysql 表中的复选框形式获得的。
This is the code I have so far, but I cannot find a way to have just one number from those values obtained:
这是我到目前为止的代码,但我找不到一种方法来从这些值中获得一个数字:
String select[] = request.getParameterValues("id");
if (select != null && select.length != 0)
{
for (int i = 0; i < select.length; i++)
{
BigDecimal total[] = new BigDecimal [select.length];
BigDecimal sum = new BigDecimal("0.00");
sum = sum.add(new BigDecimal [total.length]);
out.println(sum);
}
}
Any help would be very much appreciated please.
任何帮助将不胜感激。
回答by Reimeus
Assuming that you are adding an array of Strings
containing valid numbers you could do this:
假设您要添加一个Strings
包含有效数字的数组,您可以这样做:
BigDecimal sum = BigDecimal.ZERO;
for (int i = 0; i < select.length; i++)
{
sum = sum.add(new BigDecimal(select[i]));
}
out.println(sum);
The array total[]
is pretty much redundant. You can move your sum
declaration and out.println(sum);
out of your loop.
该阵列total[]
几乎是多余的。您可以将sum
声明out.println(sum);
移出循环。
回答by Sujay
The reason it is not working is because you're not adding the contents that you've in your selectarray properly while creating your final sum. Something like this would work:
它不起作用的原因是因为您在创建最终sum 时没有正确添加选择数组中的内容。像这样的事情会起作用:
String select[] = request.getParameterValues("id");
if (select != null && select.length != 0)
{
BigDecimal sum = BigDecimal.ZERO;
for (int i = 0; i < select.length; i++)
{
try{
sum = sum.add(new BigDecimal(select[i]));
}catch(NumberFormatException nxe){
//Handle your exception
}
}
out.println(sum);
}