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
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)); // 1num = 1.8891;System.out.println("rint(" + num + ") : " +Math.rint(num)); // 2num = 1.5;System.out.println("rint(" + num + ") : " +Math.rint(num)); // 2num = 2.5;System.out.println("rint(" + num + ") : " +Math.rint(num)); // 2num = 3.5;System.out.println("rint(" + num + ") : " +Math.rint(num)); // 2num = 2.51;System.out.println("rint(" + num + ") : " +Math.rint(num)); // 3}}
In the code above:
-
For the number , the closest value will be .
-
For the number 1.8891, the closest value will be .
-
For the number , the closest even value will be .
-
For the number , the closest even value will be .
-
For the number , the closest even value will be .
-
For the number , the closest value will be .