Is there any condition where Bigdecimal with MathContext.DECIMAL32 does not provides correct result?

377 Views Asked by At

System.out.println("Result="+new BigDecimal(((63.19* 15) + (63.37* 5))).divide(new BigDecimal(15 + 5), MathContext.DECIMAL64).doubleValue());

Result=63.23499999999999

But with MathContext.DECIMAL32 we are getting correct result, see below:

System.out.println("Result="+new BigDecimal(((63.19* 15) + (63.37* 5))).divide(new BigDecimal(15 + 5), MathContext.DECIMAL32).doubleValue());

Result=63.235

1

There are 1 best solutions below

5
On

The problem here not BigDecimal, but the fact that (63.19* 15) + (63.37* 5) is not 1264.7 but 1264.6999999999998, because the former cannot be represented as a double.

If you do

new BigDecimal("1264.7").divide(new BigDecimal("20"), MathContext.DECIMAL64)

instead, you get the desired result.