FULL PRODUCT VERSION :
Java version "1.5.0_05"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_05-b05)
Java HotSpot(TM) Client VM (build 1.5.0_05-b05, mixed mode, sharing)
ADDITIONAL OS VERSION INFORMATION :
Linux 2.6.11-6mdk #1 Tue Mar 22 16:04:32 CET 2005 i686 Intel(R) Pentium(R) 4 CPU 2.26GHz unknown GNU/Linux
A DESCRIPTION OF THE PROBLEM :
when adding two BigDecimal and requesting a rounding mode with less precision than the result and RoundingMode=HALF_UP, the result isn't always the expected.
STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
new BigDecimal("10501").add(new java.math.BigDecimal("-2.0"), new MathContext(2, RoundingMode.HALF_UP))
EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
10501 - 2.0 = 10499
When I round this with precision 2 and roundingMode=HALF_UP, I expected "1.0E+4"
ACTUAL -
I get "1.1E+4".
Curiously, 10501 - 2 (removing a trailing cero after the decimal point of the augend) shows the correct result, as occurs always when the number of trailing zeros of the augend is lower or equal than the number of trailing zeros of the addend.
Shouldn't both operations be equivalent?
REPRODUCIBILITY :
This bug can be reproduced always.
---------- BEGIN SOURCE ----------
public class AddBug{
public static void main(String[] args){
BigDecimal addend = new BigDecimal("10501");
BigDecimal augend = new BigDecimal("-2");
MathContext mc = new MathContext(2,RoundingMode.HALF_UP);
System.out.println("Using augend= "+augend);
System.out.println("Exact result:\t" + augend.add(addend));
System.out.println("Rounded result (MathContext: "+mc+")\t" + augend.add(addend,mc));
augend = new BigDecimal("-2.0");
System.out.println("Using augend= "+augend);
System.out.println("Exact result:\t" + augend.add(addend));
System.out.println("Rounded result (MathContext: "+mc+")\t" + augend.add(addend,mc));
}
}
---------- END SOURCE ----------