Why does the following code raise the exception shown below?
BigDecimal a = new BigDecimal("1.6");
BigDecimal b = new BigDecimal("9.2");
a.divide(b) // results in the following exception.
--
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
It´s a issue of rounding the result, the solution for me is the following.
For fixing such an issue I have used below code
2 is precision. Now problem was resolved.
From the Java 8 docs:
To fix, you need to do something like this:
More details: http://jaydeepm.wordpress.com/2009/06/04/bigdecimal-and-non-terminating-decimal-expansion-error/
Answer for BigDecimal throws ArithmeticException
Add MathContext object in your divide method call and adjust precision and rounding mode. This should fix your problem
I had this same problem, because my line of code was:
I change to this, reading previous Answer, because I was not writing decimal precision:
4 is Decimal Precion
AND RoundingMode are Enum constants, you could choose any of this
UP, DOWN, CEILING, FLOOR, HALF_DOWN, HALF_EVEN, HALF_UP
In this Case HALF_UP, will have this result:
You can check the
RoundingMode
information here: http://www.javabeat.net/precise-rounding-of-decimals-using-rounding-mode-enumeration/You can do
You can choose the number of bits you want either 32,64,128.
Check out this link :
http://edelstein.pebbles.cs.cmu.edu/jadeite/main.php?api=java6&state=class&package=java.math&class=MathContext