Search code examples
javabigdecimal

Difference of Two numbers - BigDecimal


I am just trying to learn more about BigDecimal, but below code makes me confuse.

Double x = 1.2;
String y = "1.2";

BigDecimal a = BigDecimal.ZERO;
BigDecimal b = BigDecimal.ZERO;

a = new BigDecimal(x);
b = new BigDecimal(y);

int res = res = b.compareTo(a);

if(res==1){
    System.out.println("Die");
}else if(res ==0){
    System.out.println("Live");
}else if (res==-1){
    System.out.println("God Loves you");
}

Result = Die

I am not ready to "Die", why BigDecimal is hell bent on killing me.


Solution

  • This statement:

    Double x = 1.2;
    

    assigns the nearest double-representable value to 1.2 to x. That's just less than 1.2 - the value 1.2 itself can't be represented exactly in binary.

    Now when you create a BigDecimal from that value, that "not quite 1.2" value is retained exactly. From the constructor's documentation:

    Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value.

    ... whereas when you use new BigDecimal("1.2") the result is exactly 1.2 - BigDecimal parses the string, and any decimal string representation can be represented exactly by BigDecimal, as that's the whole point of it.

    1.2 is slightly bigger than "the nearest double representation of 1.2" hence res is 1.