Possible Duplicate:
ArithmeticException thrown during BigDecimal.divide
This results in ArithmeticException: http://ideone.com/RXeZw
Providing a scale and rounding mode will give me the wrong result. This example should output 50.03%. How to round this correctly?
For easier reference, this is the code:
BigDecimal priceDiff = BigDecimal.ONE
.subtract(new BigDecimal(9.99)
.divide(new BigDecimal(19.99)))
.multiply(new BigDecimal(100));
System.out.println(priceDiff.toPlainString());
BigDecimal.divide(BigDecimal divisor)throws an ArithmeticException if the result cannot be exactly represented.You will have to use provide a MathContext or a RoundingMode telling how you want to handle this. For example:
works and prints
Also, note the use of the
BigDecimal(String)constructor to avoid problems when you createBigDecimalusing adoubleliteral.