问题
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;
}
回答1:
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(new BigDecimal(itemQuantity));
totalCost = totalCost.add(itemCost);
return totalCost;
}
}
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/12944559/how-to-multiply-a-bigdecimal-by-an-integer-in-java