javaintegertype-conversionbigdecimal

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


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?


Solution

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