/* * @topic T00510 Floating point rounding and precision * @brief How to avoid ArithmeticException with BigDecimal */ import java.math.BigDecimal; import java.math.RoundingMode; import java.util.InputMismatchException; public class BigDecimalMath { private static int scaleValue = 4; public static void main(String[] args) { BigDecimal bgValue = new BigDecimal("1.0"); bgValue = bgValue.setScale(scaleValue, RoundingMode.HALF_UP); BigDecimal bgDivisor = new BigDecimal("3.0"); bgDivisor = bgDivisor.setScale(scaleValue, RoundingMode.HALF_UP); // The following line generates java.lang.ArithmeticException: // Non-terminating decimal expansion; no exact representable decimal result: //BigDecimal bgResult = bgValue.divide(bgDivisor); // *** runtime error! *** // Here is the fix: we must provide the scale to the divide method: BigDecimal bgResult = bgValue.divide(bgDivisor, scaleValue, RoundingMode.HALF_UP); System.out.println("Result is " + bgResult + " and the scale is " + scaleValue); }// main }//class BigDecimalMath