I am having a problem with this code!
I am trying to run the code in java but the answer seems pretty weird.
float a=0.1F;
float b=0.2F;
if((a+b)==0.3){
System.out.println("True");
}
else{
System.out.println("False");
}
The answer is : False
But theoretically it should be return True.
The function returns True if we use values of a and b like 0.15 and 0.15 or 0.05 and 0.25.
I am confused.
I have read somewhere that languages like Java/JavaScript implements IEEE-754 number formatting! If so, then what is this formatting and what is wrong with the code? Is there anyway to change the number format?
The precision difference between floats (
a+b) and doubles (0.3) is causing the condition to be false. You could instead use(a+b)==0.3F. i.e.EDIT: In this case, even if you use
doubles the condition will befalse:Printing
0.1 + 0.2will reveal why (the number cannot be represented perfectly):