4

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?

Lion
  • 18,729
  • 22
  • 80
  • 110
  • 1
    Why are you converting it to a `float` in the first place? – NullUserException Nov 17 '11 at 01:50
  • 1
    Actually this code has no significance of its own. I just wanted to check why was this condition evaluated to false and it somewhat took me by surprise and I just decided to ask here. – Lion Nov 17 '11 at 01:57

1 Answers1

13

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).

Community
  • 1
  • 1
NullUserException
  • 83,810
  • 28
  • 209
  • 234