problem: When using BigDecimal for multiple calculations involving division. have a difficult to understand by decimals.
for example:
1/3*3
we expect is 1
but when you use BigDecimal.
we get ArithmeticException
if I add roundingMode for divide method .
we get 0.9999999999999
float result1 = 1f / 3f * 3f;
BigDecimal one = BigDecimal.valueOf(1);
BigDecimal three = BigDecimal.valueOf(3);
BigDecimal result2 = one.divide(three,64,BigDecimal.ROUND_HALF_UP).multiply(three);
System.out.println(result1);
System.out.println(result2);
The output
1.0
0.9999999999999999999999999999999999999999999999999999999999999999
I know this problem has something to do with rounding mode, but I don't know how to solve this problem
Thank you very much if you can help to propose a solution.
ps:My English is not good, I should be able to see, sorry :)