Java Math rint()

rint() returns double value that is closest in value to the argument and is equal to a mathematical integer.

Following is the syntax of rint() method.

double result = rint(double a)

Since the definition of rint() function has double datatype as argument, you can pass int, float or long as arguments; because these datatypes could implicitly promote to double.

We shall learn about some of the special cases for rint() method with examples.

Example 1 – Math.rint(double)

In the following example, we use rint() method to find the closest double value to the argument, and also equal to a mathematical integer.

Java Program

public class MathExample {
	public static void main(String[] args) {
		double a = 25.63; 
		double result = Math.rint(a);
		System.out.println(result);
	}
}

Output

26.0
ADVERTISEMENT

Example 2 – Math.rint(float)

In the following example, we pass an float value as argument to rint() method.

Java Program

public class MathExample {
	public static void main(String[] args) {
		float a = 25.12635F; 
		double result = Math.rint(a);
		System.out.println(result);
	}
}

Output

25.0

Example 3 – Math.rint() – Argument is NaN, Positive Infinity or Negative Infinity

If the argument to rint() is NaN, Positive Infinity or Negative Infinity, then the return value would be same as that of the argument.

Java Program

public class MathExample {
	public static void main(String[] args) {
		System.out.println(Math.rint(Double.NaN));
		System.out.println(Math.rint(Double.POSITIVE_INFINITY));
		System.out.println(Math.rint(Double.NEGATIVE_INFINITY));
	}
}

Output

NaN
Infinity
-Infinity

Conclusion

In this Java Tutorial, we learned about Java Math.rint() function, with example programs.