Here is my code snippet.
If amtIn is 100 and amtOut is 20, then it works fine.
But if amtIn is 100 and amtOut is 120, then it will throw exception unexpectedly
According to JavaDoc...
When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.)
As a corollary of computing the exact result, the rounding mode setting of a MathContext object with a precision setting of 0 is not used and thus irrelevant. In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3.
If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.
Owing to 100/120 has a nonterminating decimal expansion, so it will throw java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result
To resolve this problem, you can set precision to 2, and set rounding mode to RoundingMode.HALF_UP (precision and rounding mode depends on your requirement)