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; }
intValue()converts this BigDecimal to an int. This conversion is analogous to the narrowing primitive conversion from double to short. Any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned.
math. BigDecimal. doubleValue() is an in-built function which converts the BigDecimal object to a double. This function converts the BigDecimal to Double.
A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001 ) could result in the 0.001 being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With