What is Math.rint in Java?

The rint method in Java is used to get the closest floating point value that is equal to the integerwhole number; a number without fractions.

The rint method is a static method available in the Math class.

Syntax

Math.rint(double val)

The rint method returns the closest value of the val argument.

  • If the value after the decimal is less than .5, then the number is rounded down. For example, the closest integer for the number 1.3 is 1.0.

  • If the value after the decimal is greater than .5, then the number is rounded up. For example, the closest integer for the number 1.51 is 2.0.

  • If the value after the decimal is equal to .5, then the argument is rounded to the nearest even value. For example:

    • If the argument is 1.5, then the nearest even value is 2.0.

    • If the argument is 2.5, then the nearest even value is 2.0.

    • If the argument is 3.5, then the nearest even value is 4.0.

Example

class RIntExample {
public static void main( String args[] ) {
double num = 1.345;
System.out.println("rint(" + num + ") : " +Math.rint(num)); // 1
num = 1.8891;
System.out.println("rint(" + num + ") : " +Math.rint(num)); // 2
num = 1.5;
System.out.println("rint(" + num + ") : " +Math.rint(num)); // 2
num = 2.5;
System.out.println("rint(" + num + ") : " +Math.rint(num)); // 2
num = 3.5;
System.out.println("rint(" + num + ") : " +Math.rint(num)); // 2
num = 2.51;
System.out.println("rint(" + num + ") : " +Math.rint(num)); // 3
}
}

In the code above:

  • For the number 1.3451.345, the closest value will be 1.01.0.

  • For the number 1.8891, the closest value will be 2.02.0.

  • For the number 1.51.5, the closest even value will be 2.02.0.

  • For the number 2.52.5, the closest even value will be 2.02.0.

  • For the number 3.53.5, the closest even value will be 4.04.0.

  • For the number 2.512.51, the closest value will be 3.03.0.

Free Resources