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

筅森魡賤 提交于 2020-01-01 09:12:23

问题


I have to integrate my web application with a payment gateway. I want to input total amount in USD and then convert it into Cents as my payment gateway library accepts amount in Cents (of type Integer). I found that Big Decimal in java is best way for manipulation of currency. Currently I take input as say USD 50 and convert it to Integer like this:

BigDecimal rounded = amount.setScale(2, BigDecimal.ROUND_CEILING);
BigDecimal bigDecimalInCents = rounded.multiply(new BigDecimal("100.00"));
Integer amountInCents = bigDecimalInCents.intValue();

Is this the correct way of converting USD to Cents or I should do it in some other way?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/30398092/what-is-the-best-way-to-convert-dollars-big-decimal-in-cents-integer-in-java

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