Wrong results for division in Java

When dividing two integers, Java uses integer division. In integer division, the result is also an integer. The result is truncated (the fractional part is thrown away) and not rounded to the closest integer.

class Division {
public static void main( String args[] ) {
int i = 37;
int j = 10;
int r = i / j;
System.out.println(r);
}
}

To get actual floating point result

Cast the numerator (or denominator) to double:

class Division {
public static void main( String args[] ) {
int i = 37;
int j = 10;
double r = (double) i / j;
System.out.println(r);
}
}

To get rounded result

Following the same approach as above, cast the resulting double into a long using Math.round:

class Division {
public static void main( String args[] ) {
int i = 37;
int j = 10;
long r = Math.round((double) i / j);
System.out.println(r);
}
}

Free Resources

Attributions:
  1. undefined by undefined