troubleshooting Question

# BigDecimal division rounding

Java
Hello!

Take a look at this code:

package crap;
import java.math.BigDecimal;
public class BDCalc {
public static void main(String[] args){
// Declare primitives
double const1 = 1.2991;
double val1 = 0.9;
double val2 = 0.5;

// Divide with primitives:
double result1 = val1/const1;
System.out.println("Primitives ex. 1: " + result1);
double result2 = val2/const1;
System.out.println("Primitives ex. 2: " + result2);

// Declare BigDecimals with same values
BigDecimal bdConst = new BigDecimal(const1);
BigDecimal bdVal1 = new BigDecimal(val1);
BigDecimal bdVal2 = new BigDecimal(val2);

// Divide with BigDecimal
BigDecimal bdResult1 = bdVal1.divide(bdConst, BigDecimal.ROUND_HALF_UP);
System.out.println("BigDecimal ex.1: " + bdResult1.doubleValue());
BigDecimal bdResult2 = bdVal2.divide(bdConst, BigDecimal.ROUND_HALF_UP);
System.out.println("BigDecimal ex.2: " + bdResult2.doubleValue());
}
}

At least for me, it produces the following output:

Primitives ex. 1: 0.6927873142945117
Primitives ex. 2: 0.3848818412747287
BigDecimal ex.1: 0.6927873142945117
BigDecimal ex.2: 0.4

Can someone for the life of me explain why the last division - as the only one - is rounded to 0.4 ?!

Best regards to all!
Mick Barry
Java Developer
###### Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.