Bigdecimal for financial computing and non-performing computing

I am sure that this will be a simple question for an answer, but I cannot let my life decide what needs to be done. So here it is: assuming we are following the “best practice” of using BigDecimal for financial calculations, how can you handle things (calculations) that throw an exception?

As an example: suppose I need to divide the “user amount” by investment in bonds between “n” different entities. Now consider the case when a user sends $ 100 to invest in 3 bonds. Equivalent code would look like this:

 public static void main(String[] args) throws Exception { BigDecimal bd1 = new BigDecimal("100.0"); BigDecimal bd2 = new BigDecimal("3"); System.out.println(bd1.divide(bd2)); } 

But, as we all know, this piece of code throws an ArithmeticException , because the separation does not end. How to handle such scenarios in your code when using infinite precision data types during calculations?

TIA
Sasuke

UPDATE: Given that RoundingMode will help fix this problem, the next question is: why is 100.0 / 3 not 33.33 instead of 33.3? Wouldn't 33.33 be a “more” exact answer since you expect 33 cents instead of 30? Is there a way I can configure this?

+4
source share
3 answers

The answer is to use one of the BigDecimal.divide() methods that define RoundingMode .

For example, the following rounding mode is even half or bankers rounding (but half up or one of the other rounding modes may be more appropriate depending on requirements) and is rounded to two decimal places:

 bd1.divide(bd2, 2, RoundingMode.HALF_EVEN); 
+7
source

divide has an overload that accepts rounding mode. You need to choose one. I believe that “half even” is the most commonly used for cash payments.

+2
source
 bd1.divide(bd2, 5, BigDecimal.ROUND_FLOOR) 

This is an example, depending on the desired rounding.

+1
source

All Articles