在 java 中将美元(大数小数)转换为美分(整数)的最佳方法是什么?

What is the best way to convert Dollars (Big Decimal) in Cents (Integer) in java?

我必须将我的 Web 应用程序与支付网关集成。我想以美元输入总金额,然后将其转换为美分,因为我的支付网关库接受美分金额(Integer 类型)。我发现 java 中的 Big Decimal 是操纵货币的最佳方式。目前我输入 50 美元并将其转换为 Integer,如下所示:

BigDecimal rounded = amount.setScale(2, BigDecimal.ROUND_CEILING);
BigDecimal bigDecimalInCents = rounded.multiply(new BigDecimal("100.00"));
Integer amountInCents = bigDecimalInCents.intValue();

这是将美元换算成美分的正确方法吗?还是我应该用其他方法换算?

包含我以下几点的最简单的是:

public static int usdToCents(BigDecimal usd) {
    return usd.movePointRight(2).intValueExact();
}

我推荐 intValueExact,因为如果信息丢失(如果您处理的交易超过 21,474,836.47 美元),这将引发异常。这也可用于捕获丢失的分数。

我还会考虑接受零分和四舍五入的值是否正确。我会说不,客户端代码必须提供有效的计费金额,所以如果我需要自定义例外,我可能会这样做:

public static int usdToCents(BigDecimal usd) {
    if (usd.scale() > 2) //more than 2dp
       thrown new InvalidUsdException(usd);// because was not supplied a billable USD amount
    BigDecimal bigDecimalInCents = usd.movePointRight(2);
    int cents = bigDecimalInCents.intValueExact();
    return cents;
}

您还应该考虑最小化 Round-off errors

int amountInCent = (int)(amountInDollar*100 + 0.5);
LOGGER.debug("Amount in Cents : "+ amountInCent );

上述解决方案可能对您有所帮助。