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; }
Advertisement
Answer
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; } }