0

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

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
A_Coder
  • 3
  • 3
  • 1
    For me, the problem seems to be in `63.19` and `63.37` float decimal points. Have you checked the result of this operations If you create the `BigDecimal`s from `String`s? – Luiggi Mendoza May 06 '15 at 17:25
  • I Know create the BigDecimals from Strings is best practice. but atleast i want 1 situation where Bigdecimal with MathContext.DECIMAL32 does not provides correct result? – A_Coder May 06 '15 at 17:44
  • Start by using the class in the right way. I could only say that NO, there's no way MathContext.DECIMAL32 will provide a correct result. In fact, the only way to obtain *wrong* results while using `BigDecimal` is if you use `double` to create an instance of it. – Luiggi Mendoza May 06 '15 at 17:45

1 Answers1

1

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.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
  • 1
    `new BigDecimal(1264.7)` won't give you the right answer either. It has to be `new BigDecimal("1264.7")`, passed in as a `String`. – Louis Wasserman May 06 '15 at 17:27
  • @LouisWasserma I've changed my answer, as you are right that you should use the `String` constructor. – Paul Boddington May 06 '15 at 17:30
  • @LouisWasserman I was confusing `new BigInteger(double)` with `BigInteger.valueOf(1264.7)` which confusingly does give you `1264.7`. – Paul Boddington May 06 '15 at 17:33
  • `BigDecimal.valueOf` more-or-less papers over the issues with double representation; use the string constructor if it's at all possible. – Louis Wasserman May 06 '15 at 17:38
  • I Know create the BigDecimals from Strings is best practice. but atleast i want 1 situation where Bigdecimal with MathContext.DECIMAL32 does not provides correct result? – A_Coder May 06 '15 at 17:43