Java - Math.round() Method



Description

The Java Math round(double a) returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. Following are the special cases to consider −

  • If the argument is NaN, the result is 0.

  • If the argument is negative infinity or any value less than or equal to the value of Long.MIN_VALUE, the result is equal to the value of Long.MIN_VALUE.

  • If the argument is positive infinity or any value greater than or equal to the value of Long.MAX_VALUE, the result is equal to the value of Long.MAX_VALUE.

Syntax

This method has the following variants −

public static long round(double d)
public static int round(float f)

Parameters

Here is the detail of parameters −

  • d − A double or float primitive data type.

  • f − A float primitive data type.

Return Value

  • This method returns the closest long or int, as indicated by the method's return type, to the argument.

Example 1

In this example, we're showing the usage of Math.round() method to get the closet long in value to given double number. We've created three double variables d1, d2, d3 and initialized them with different values. Then using Math.round() 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.400;
     
      System.out.println(Math.round(d1));
      System.out.println(Math.round(d2));
      System.out.println(Math.round(d3));	  
   }
}

This will produce the following result −

Output

101
101
100

Example 2

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

public class Test { 
   public static void main(String args[]) {
      float d1 = (float)100.675;
      float d2 = (float)100.500;
      float d3 = (float)100.400;
     
      System.out.println(Math.round(d1));
      System.out.println(Math.round(d2));
      System.out.println(Math.round(d3));	  
   }
}

This will produce the following result −

Output

101
101
100

Example 3

In this example, we're showing the usage of Math.round() 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.round() 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.round(d1));
      System.out.println(Math.rint(d2)); 
   }
}

This will produce the following result −

Output

0
0.0
java_numbers.htm
Advertisements