最简单的包括我的要点如下:
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;
}