Possible Duplicate:
Java Integer Division, How do you produce a double?
double wang = 3 / 2;
Log.v("TEST", "Wang: " + Double.toString(wang));
Logcat output…
07-04 09:01:03.908: VERBOSE/TEST(28432): Wang: 1.0
I’m sure there’s an obvious answer to this and probably I’m just tired from coding all night but this has me stumped.
In many languages, Java being one of them, the way you write a number in an expression decides what type it gets. In Java, a few of the common number types behave like this1:
Thus, when you declare
3 / 2, you’re really saying(the integer 3) / (the integer 2). Java performs the division, and finds the result to be1(i.e.the integer 1…) since that’s the result of dividing 3 and 2 as integers. Finally,the integer 1is cast tothe double 1.0dwhich is stored in your variable.To work around this, you should (as many others have suggested) instead calculate the quotient of
or, in Java syntax,
1 Source: The Java Tutorial from Oracle