What is the best way to convert Dollars (Big Decimal) in Cents (Integer) in java?

你说的曾经没有我的故事 提交于 2019-12-04 03:33:12

The simplest which includes my points below is:

public static int usdToCents(BigDecimal usd) {
    return usd.movePointRight(2).intValueExact();
}

I'd recommend intValueExact as this will throw an exception if information will be lost (in case you're processing transactions above $21,474,836.47). This can also be used to trap lost fractions.

I'd also consider whether is it correct to accept a value with a fraction of a cent and round. I'd say no, the client code must supply a valid billable amount, so I might do this if I needed a custom exception for that:

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

You should also consider minimizing Round-off errors.

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

This above solution might help you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!