Variables with Bigdecimal

Asked

Viewed 1,880 times

6

I am trying to add a value in a variable of type Bigdecimal, however independent 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);
    }
  • What is the value of preco that you used?

  • The price is in Bigdecimal

2 answers

5


The problem is that you cannot modify the value BigDecimal, it is immutable. Therefore, you must create a new BigDecimal to store the result, which must be the objective of its variable valorTotal.

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

BigDecimal preco = new BigDecimal(10);

And modifying his method to:

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

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

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

The score is 100. Version on the ideone: link.

3

This happens because the method add only returns a Bigdecimal.

To correct, simply assign the sum to the total value:

valorTotal = valorTotal.Add(newQtd2);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.