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?
source share