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);}}
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);}}
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