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

问题描述 投票:7回答:2

我必须将我的Web应用程序与支付网关集成。我想以美元输入总金额,然后将其转换为美分,因为我的支付网关库接受的数量为Cents(类型为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();

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

java integer type-conversion bigdecimal
2个回答
9
投票

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

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;
}

0
投票

您还应该考虑尽量减少Round-off errors

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

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

© www.soinside.com 2019 - 2024. All rights reserved.