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);
}
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Attributions:
  1. undefined by undefined