Precision and scale in BigDecimal and MathContext

Lately, after publishing the previous post, a friend of mine passed me a snipped of BigDecimal code. He was wondering, why the following execution: BigDecimal a = new BigDecimal(2.9); BigDecimal b = new BigDecimal(4000); MathContext mc = new MathContext(2, RoundingMode.HALF_DOWN); BigDecimal r1 = a.multiply(b, mc); BigDecimal r2 = a.multiply(b).setScale(2, RoundingMode.HALF_DOWN); System.out.println("r1 = " + r1); System.out.println("r2 = " + r2); is returning different values for r1 and r2: r1 = 1....

February 5, 2011 · 2 min