The following simple code in Java contains hardly 3 statements that returns unexpectedly false though it looks like that it should return true.
package temp;
final public class Main
{
public static void main(String[] args)
{
long temp = 2000000000;
float f=temp;
System.out.println(f<temp+50);
}
}
The above code should obviously display true on the console but it doesn’t. It displays false instead. Why?
This happens because floating point arithmetic != real number arithmetic.
When
fis assigned2000000000, it gets converted to2.0E9. Then when you add 50 to2.0E9, its value doesn’t change. So actually,(f == temp + 50)istrue.If you need to work with large numbers but require precision, you’ll have to use something like
BigDecimal:Will print
trueas one would expected.(although in your case I don’t know why you’d need to use a datatype other than
long).