70

How do you multiply a BigDecimal by an integer in Java? I tried this but its not correct.

import java.math.BigDecimal;
import java.math.MathContext;

public class Payment {
    int itemCost;
    int totalCost = 0;

    public BigDecimal calculateCost(int itemQuantity,BigDecimal itemPrice){
        itemCost = itemPrice.multiply(itemQuantity);
        totalCost = totalCost + itemCost;
    return totalCost;
   }
Adesh
  • 937
  • 4
  • 11
  • 17

3 Answers3

106

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
{
    BigDecimal itemCost  = BigDecimal.ZERO;
    BigDecimal totalCost = BigDecimal.ZERO;

    public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
    {
        itemCost  = itemPrice.multiply(BigDecimal.valueOf(itemQuantity));
        totalCost = totalCost.add(itemCost);
        return totalCost;
    }
}
Juvanis
  • 25,802
  • 5
  • 69
  • 87
  • Heh. I was right about the `BigDecimal(int)` constructor. :P – Robert Harvey Oct 17 '12 at 22:55
  • 14
    Using `BigDecimal.valueOf(itemQuantity)`, instead of the constructor, will reuse BigDecimals zero through ten, avoiding probable new object construction. – Crunch Aug 28 '15 at 00:47
4

If I were you, I would set the scale of the BigDecimal so that I dont end up on lengthy numbers. The integer 2 in the BigDecimal initialization below sets the scale.

Since you have lots of mismatch of data type, I have changed it accordingly to adjust.

class Payment   
{
      BigDecimal itemCost=new BigDecimal(BigInteger.ZERO,  2);
      BigDecimal totalCost=new BigDecimal(BigInteger.ZERO,  2);

     public BigDecimal calculateCost(int itemQuantity,BigDecimal itemPrice)
       { 
           BigDecimal   itemCost = itemPrice.multiply(new BigDecimal(itemQuantity)); 
             return totalCost.add(itemCost); 
       }
  }

BigDecimals are Object , not primitives, so make sure you initialize itemCost and totalCost , otherwise it can give you nullpointer while you try to add on totalCost or itemCost

Jimmy
  • 2,589
  • 21
  • 31
  • +1 for emphasizing the issue about the scale. While you're at it, please note that your multiplication will end up with `itemCost` having a scale of `4`, not `2`: "Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale())" https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#multiply-java.math.BigDecimal- – pyb Jan 13 '16 at 15:38
2

First off, BigDecimal.multiply() returns a BigDecimal and you're trying to store that in an int.

Second, it takes another BigDecimal as the argument, not an int.

If you just use the BigDecimal for all variables involved in these calculations, it should work fine.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953