msr msr - 7 months ago 8
Java Question

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

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

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


Obviously I want
b=0.3
for the output but here's what I get
b=1
.

What?! Why does this happens?

If I make:

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


I get the right result which is
b=0.3
.

What's going wrong here?

Answer

You're using integer division.

Try 7.0/10 instead.

Comments