Simple division in Java - is this a bug or a feature?

rasgo picture rasgo · May 26, 2010 · Viewed 188.6k times · Source

I'm trying this simple calculation in a Java application:

System.out.println("b=" + (1 - 7 / 10));

Obviously I expect the output to be b=0.3, but I actually get b=1 instead.

What?! Why does this happen?

If I write:

System.out.println("b=" + (1 - 0.7));

I get the right result, which is b=0.3.

What's going wrong here?

Answer

Xavier Ho picture Xavier Ho · May 26, 2010

You're using integer division.

Try 7.0/10 instead.