我必须将我的网络应用程序与支付网关集成。我想输入美元总金额,然后将其转换为美分,因为我的支付网关库接受美分金额(类型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();
这是将美元兑换成美分的正确方法还是我应该以其他方式进行?
最简单的包括我的以下观点:
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)