Java - Math.rint() Method



Description

The Java Math rint(double a) returns the double value that is closest in value to the argument and is equal to a mathematical integer. If two double values that are mathematical integers are equally close, the result is the integer value that is even. Following are special cases to consider −

  • If the argument value is already equal to a mathematical integer, then the result is the same as the argument.

  • If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.

Syntax

public static double rint(double d)

Parameters

Here is the detail of parameters −

  • d − it accepts a double value as parameter.

Return Value

  • This method returns the integer that is closest in value to the argument. Returned as a double.

Example 1

In this example, we're showing the usage of Math.rint() method to get the closet integer in value to given double number. We've created three double variables d1, d2, d3 and initialized them with different values. Then using Math.rint() method we're printing the required value of the given doubles.

public class Test { 
   public static void main(String args[]) {
      double d1 = 100.675;
      double d2 = 100.500; 
      double d3 = 100.200; 	  

      System.out.println(Math.rint(d1));
      System.out.println(Math.rint(d2));
      System.out.println(Math.rint(d3));	  
   }
}

This will produce the following result −

Output

101.0
100.0
100.0

Example 2

In this example, we're showing the usage of Math.rint() method to get the closet integer in value to given float number. We've created three float variables d1, d2 and d3 and initialized them with different values. Then using Math.rint() method we're printing the required value of the given doubles.

public class Test { 
   public static void main(String args[]) {
      float d1 = (float)100.675;
      float d2 = (float)100.500; 
      float d3 = (float)100.200; 	  

      System.out.println(Math.rint(d1));
      System.out.println(Math.rint(d2));
      System.out.println(Math.rint(d3));	  
   }
}

This will produce the following result −

Output

101.0
100.0
100.0

Example 3

In this example, we're showing the usage of Math.rint() method to check the case of 0. We've created one double and one float variables d1, d2 and initialized them with zero values. Then using Math.rint() method we're printing the required value of the given variables.

public class Test { 
   public static void main(String args[]) {
      float d1 = (float) 0.0;
      double d2 = 0.0;    

      System.out.println(Math.rint(d1));
      System.out.println(Math.rint(d2)); 
   }
}

This will produce the following result −

Output

0.0
0.0
java_numbers.htm
Advertisements