Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple Java code that returns unexpectedly false while it is intened to return true

Tags:

java

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?

like image 729
Lion Avatar asked Dec 10 '22 04:12

Lion


1 Answers

This happens because floating point arithmetic != real number arithmetic.

When f is assigned 2000000000, it gets converted to 2.0E9. Then when you add 50 to 2.0E9, its value doesn't change. So actually, (f == temp + 50) is true.

If you need to work with large numbers but require precision, you'll have to use something like BigDecimal:

long temp = 2000000000;
BigDecimal d = new BigDecimal(temp);

System.out.println(d.compareTo(new BigDecimal(temp+50)) < 0);

Will print true as one would expected.

(although in your case I don't know why you'd need to use a datatype other than long).

like image 96
NullUserException Avatar answered Dec 11 '22 16:12

NullUserException