0

I select a number column in database. For example:

                BigDecimal total_price_bg;
                BigDecimal unit_price_bg;

                if (results.next()) {
                    unit_price_bg = results.getBigDecimal("UNIT_PRICE");
                    total_price_bg = unit_price_bg.multiply(unit_price_bg); // I have trouble here..
                    System.out.println(total_price_bg);
                }    

First row could contain 10.25, second row 7.03 and third row could contain 371.09. How do I multiply big decimal many times with same variable?? Is it actually possible? Thanks in advance.

sg552
  • 1,521
  • 6
  • 32
  • 59
  • Why not initializing `total_price_bg` at `BigDecimal.ONE` then `total_price_bg = total_price_bg.multiply(results.getBigDecimal("UNIT_PRICE")))` – Arnaud Denoyelle Feb 19 '16 at 13:47

1 Answers1

2

Do you mean like this?

            BigDecimal total_price_bg = BigDecimal.ONE;

            while (results.next()) {
                BigDecimal unit_price_bg = results.getBigDecimal("UNIT_PRICE");
                total_price_bg = total_price_bg.multiply(unit_price_bg.pow(2)); 
            }    
            System.out.println(total_price_bg);

This continually compounds the value of UNIT_PRICE squared into a variable total_price_bg. I squared the value of unit_price_bg because I noticed you were multiplying it times itself, but maybe you meant:

            BigDecimal total_price_bg = BigDecimal.ONE;

            while (results.next()) {
                BigDecimal unit_price_bg = results.getBigDecimal("UNIT_PRICE");
                total_price_bg = total_price_bg.multiply(unit_price_bg); 
            }    
            System.out.println(total_price_bg);
Neil
  • 5,762
  • 24
  • 36
  • yes the total of `10.25 * 7.03 * 371.09` should be `26739.817675`. Thanks I will try your solution. – sg552 Feb 19 '16 at 13:58
  • @sg552 Definitely a wise choice to use BigDecimal. You may be dealing with smaller numbers now, but it may not always be that way and BigDecimal is the only type that can guarantee that there will be no overflow. – Neil Feb 19 '16 at 14:01