在Java中以美分(整数)转换美元(大十进制)的最佳方法是什么?

nik*_*uja 8 java integer type-conversion bigdecimal

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

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

这是将美元转换为美分的正确方法还是应该以其他方式实现?

wes*_*ton 10

最简单的包括我的要点如下:

public static int usdToCents(BigDecimal usd) {
    return usd.movePointRight(2).intValueExact();
}
Run Code Online (Sandbox Code Playgroud)

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