如何在Java中将BigDecimal乘以整数

Ade*_*esh 53 java bigdecimal

如何在Java中将BigDecimal乘以整数?我试过这个,但不正确.

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;
   }
Run Code Online (Sandbox Code Playgroud)

Juv*_*nis 82

您的代码中存在许多类型不匹配,例如尝试将int值放在BigDecimal需要的位置.您的代码的更正版本:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 使用`BigDecimal.valueOf(itemQuantity)`而不是构造函数,将从零到十重复使用BigDecimals,避免可能的新对象构造. (10认同)