What causes "Non-terminating decimal expansion" exception from BigDecimal.divide?
Here's the problem
bd1.divide(bd2)
You need to use one of the overloaded divide()
methods that takes a rounding mode (in various forms) - you cannot do the rounding after the division because with a nonterminating fraction the intermediate result would either already need to be rounded, or require infinite storage space.
The problem is caused by an operation (division) that would result in a recurring decimal.
The solution is to specify a scale when performing a division, for example:
BigDecimal one = new BigDecimal("1");
BigDecimal three = new BigDecimal("3");
BigDecimal oneDivThree = one.divide(three, 200, RoundingMode.HALF_UP);
Non-terminating decimal need rounding
When using divide
you should use a MathContext
with RoundingMode
in case the exact result has an infinite number of decimals.
Such is your case:
MathContext mc = new MathContext(2, RoundingMode.HALF_UP) ;
BigDecimal bd3 = bd1.divide(bd2, mc);
Alternatively call divide
with a rounding mode to use the scale of the numerator (bd1
in the example below):
BigDecimal bd3 = bd1.divide(bd2, RoundingMode.HALF_UP);