Peter Penzov Peter Penzov - 1 month ago 7
Java Question

How to calculate BigDecimal

I created this JUnit test in order to test how to calculate all values from Objects with value BigDecimal.

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Test;

public class BigDecimalTest
{
private BigDecimal sumAmounts(List<ExpressCheckout> myList)
{
BigDecimal total = new BigDecimal(BigInteger.ZERO);
for (ExpressCheckout item : myList)
{
total.add(item.getAmount());
}
return total;
}

@Test
public void testBigDecimalTest()
{
try
{
List<ExpressCheckout> list = new ArrayList<>();
for (int i = 0; i < 12; i++)
{
ExpressCheckout obj = new ExpressCheckout();
obj.setCurrency("USD");

Random rand = new Random();

int n = rand.nextInt(50) + 1;
obj.setAmount(new BigDecimal(n));
obj.setQuantity(1);
obj.setName("test name");
obj.setDescription("test description");
list.add(obj);
}

BigDecimal sumAmounts = sumAmounts(list);

System.out.println(">>>>>>>>>>>>>>>>>>>> sumAmounts " + sumAmounts.toString());

}
catch (Exception ex)
{
Logger.getLogger(BigDecimalTest.class.getName()).log(Level.SEVERE, null, ex);
}
}

public class ExpressCheckout
{
String currency;
BigDecimal amount;
int quantity;
String name;
String description;

public ExpressCheckout()
{
}

public ExpressCheckout(String currency, BigDecimal amount, int quantity, String name, String description)
{
this.currency = currency;
this.amount = amount;
this.quantity = quantity;
this.name = name;
this.description = description;
}

public String getCurrency()
{
return currency;
}

public void setCurrency(String currency)
{
this.currency = currency;
}

public BigDecimal getAmount()
{
return amount;
}

public void setAmount(BigDecimal amount)
{
this.amount = amount;
}

public int getQuantity()
{
return quantity;
}

public void setQuantity(int quantity)
{
this.quantity = quantity;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public String getDescription()
{
return description;
}

public void setDescription(String description)
{
this.description = description;
}
}

}


For some reason I get result
sumAmounts 0
Any idea why I get this result and how I can fix it?
The result should be calculated from all BigDecimal values from the Java List.

SMA SMA
Answer

BigDecimal in java is immutable, hence your statement in sumAmounts method as below:

total.add(item.getAmount());

needs to change to:

total = total.add(item.getAmount());