Search code examples
javabigdecimal

adding values from a BigDecimal [ ]


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.

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.


Solution

  • Assuming that you are adding an array of Strings containing valid numbers you could do this:

    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.