BigDecimal error
-
Write a code in which arithmetic operations are to be performed. Everything works right except splitting. ♪ ♪ Sends such an exception if you divide a smaller number by more:
This is the code.
public class GoMath {
public <T extends Number> T getResultMath(T arg1, T arg2, String op) { BigDecimal bigArg1 = new BigDecimal(arg1 instanceof Integer ? arg1.intValue(): arg1.doubleValue()); BigDecimal bigArg2 = new BigDecimal(arg2 instanceof Integer ? arg2.intValue() : arg2.doubleValue()); BigDecimal bigRes = null; switch (op) { case "/": { if (arg1.intValue() == 0 || arg2.intValue() == 0) { try { throw new DivZeroException("Неможливе ділення на 0"); } catch (DivZeroException dz) { System.out.print(dz.getMessage()); } } bigRes = bigArg1.divide(bigArg2); break; } case "*": { bigRes = bigArg1.multiply(bigArg2); break; } case "+": { bigRes = bigArg1.add(bigArg2); break; } case "-": { bigRes = bigArg1.subtract(bigArg2); break; } } if(arg1 instanceof Integer && arg2 instanceof Integer) { return (T) new Integer(bigRes.intValue()); } if(arg1 instanceof Integer && arg2 instanceof Integer && arg1.intValue() < arg2.intValue() && op.equals("/")) { return (T) new Double(bigRes.doubleValue()); } return (T) new Double(bigRes.doubleValue()); }
}
in main :
public class RunTet
{
public static void main(String[] args)
{
Number a = 6, b = 7;GoMath gm = new GoMath(); System.out.print(gm.getResultMath(a, b, "/")); }
}
The result is a mistake:
Error text:
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1690)
at math_action_realization.GoMath.getResultMath(GoMath.java:30)
at math_action_realization.RunTet.main(RunTet.java:12)How can you fix that?
-
In the BigDecimals, please indicate how to round up in the method .divide(...). Otherwise, ArithmeticException may be obtained if there is no precise rounded result, e.g. 1/3. Thus, it is always necessary to:
a = b.divide(c, decimals, rounding);