在Java中转换美元(整数)的美元(大十进制)的最佳方法是什么?
我必须将我的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();
这是将美元转换为美分的正确方法还是应该以其他方式实现?
最简单的包括我的要点如下:
public static int usdToCents(BigDecimal usd) { return usd.movePointRight(2).intValueExact(); }
我建议使用intValueExact
因为如果信息丢失(如果您处理超过21,474,836.47美元的交易),这将抛出exception。 这也可用于捕获丢失的分数。
我还要考虑接受一个分数和一个半分的值是否正确。 我会说不,客户端代码必须提供有效的可结算金额,所以如果我需要一个自定义exception,我可能会这样做:
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 );
以上解决方案可能对您有所帮助