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

I need to integrate my web application with a payment gateway. I want to enter the total amount in US dollars, and then convert it to Cents, since my payment gateway library accepts the amount in Cents (such as Integer ). I found that Big Decimal in java is the best way to manipulate currency. Currently, I take the input, they say, $ 50 and convert it to Integer as follows:

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

Is this the right way to convert US dollars to cents, or should I do it in some other way?

+6
source share
2 answers

The simplest one that includes my points below:

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

I would recommend intValueExact as this will throw an exception if the information is lost (if you process transactions above $ 21,474,836.47). It can also be used to trap lost fractions.

I also wondered if it was right to accept the value with a fraction of a percent and a round. I would say no, the client code must provide a valid billable amount, so I could do this if I needed a special 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; } 
+7
source

You should also consider minimizing Round-off errors .

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

This solution may help you.

0
source

Source: https://habr.com/ru/post/987750/


All Articles