Variables with BigDecimal

6

I'm trying to add a value to a variable of type BigDecimal, however regardless of the calculation it results in 0.

Sample code:

    BigDecimal valorTotal = new BigDecimal(0);

    public void adicionarVenda(int idProduto, int quantidade) {
         BigDecimal newQtd = new BigDecimal(quantidade);
         BigDecimal newQtd2 = newQtd.multiply(preco);
         valorTotal.add(newQtd2);
         System.out.println(valorTotal);
    }
    
asked by anonymous 04.04.2014 / 05:01

2 answers

5

The problem is that you can not change the value BigDecimal , it is immutable. So you should create a new BigDecimal to store the result, which should be the goal of your valorTotal variable.

Example:
Assuming that preco is 10 and that quantidade is also 10:

BigDecimal preco = new BigDecimal(10);

And modifying your method to:

      BigDecimal newQtd = new BigDecimal(quantidade);
      BigDecimal newQtd2 = newQtd.multiply(preco);

      valorTotal = valorTotal.add(newQtd2); // <<

      System.out.println(valorTotal.toString());

The result is 100. Version on ideone: link .

    
04.04.2014 / 05:57
3

This happens because the add only returns a BigDecimal.

To fix, you only need to assign the sum to the total value:

valorTotal = valorTotal.Add(newQtd2);
    
04.04.2014 / 05:56