I'm trying to get predictable behavior with rounding BigDecimal numbers to 15th digit. As a result I'm getting some either round up or round down.
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class NumberTest {
public static void main(String[] args) {
String pattern = "##############0.0##############";
MathContext mc = new MathContext(15, RoundingMode.HALF_UP);
NumberFormat numberFormat = new DecimalFormat(pattern);
BigDecimal n1 = new BigDecimal(0.0452641706926935, mc);
n1.setScale(15, BigDecimal.ROUND_HALF_UP);
BigDecimal n2 = new BigDecimal(0.0123456789012345, mc);
n2.setScale(15, BigDecimal.ROUND_HALF_UP);
System.out.println("n1: "+n1+" ==> "+n1.doubleValue()+"="+numberFormat.format(n1.doubleValue()));
System.out.println("n3: "+n2+" ==> "+n2.doubleValue()+"="+numberFormat.format(n2.doubleValue()));
}
}
Output of my result:
n1: 0.0452641706926935 ==> 0.0452641706926935=0.045264170692694
n2: 0.0123456789012345 ==> 0.0123456789012345=0.012345678901234
n1 - rounded up n2 - rounded down
What am I missing?
thank you.