java - Difference of Two numbers - BigDecimal -


i trying learn more bigdecimal, below code makes me confuse.

double x = 1.2; string y = "1.2";  bigdecimal = bigdecimal.zero; bigdecimal b = bigdecimal.zero;  = 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 not ready "die", why bigdecimal hell bent on killing me.

this statement:

double x = 1.2; 

assigns nearest double-representable value 1.2 x. that's less 1.2 - value 1.2 can't represented in binary.

now when create bigdecimal value, "not quite 1.2" value retained exactly. constructor's documentation:

translates double bigdecimal exact decimal representation of double's binary floating-point value.

... whereas when use new bigdecimal("1.2") result exactly 1.2 - bigdecimal parses string, , decimal string representation can represented bigdecimal, that's whole point of it.

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


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -