Unexpected result in long/int division

alex picture alex · Sep 7, 2012 · Viewed 32.7k times · Source

I have values like this:

long millis = 11400000;
int consta = 86400000;
double res = millis/consta;

The question is: why res equals 0.0 (instead of ca. 0.131944)? It's stored in double so there should be no rounding right?

Answer

Kamran Amini picture Kamran Amini · Sep 7, 2012

When you are using a binary operator, both arguments should be of a same type and the result will be in their type too. When you want to divide (int)/(long) it turns into (long)/(long) and the result is (long). you shouldmake it (double)/(long) or (int)/(double) to get a double result. Since double is greater that int and long, int and long will be turned into double in (double)/(long) and (int)/(double)