Java Math round() method with Example


The java.lang.Math.round() is a built-in math function which returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result after adding 1/2, and casting the result to type long.

  • 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 Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

Syntax:

public static int round(float val)
Parameter: 
val - floating-point value to be rounded to an integer. 

Returns:
The method returns the value of the argument rounded to the nearest int value.



Example: To show working of java.lang.Math.round() function

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate working
// of java.lang.Math.round() method
import java.lang.Math;
    
class Gfg {
    
    // driver code
    public static void main(String args[])
    {
        // float numbers
      float x = 4567.9874f;
  
      // find the closest int for these floats
      System.out.println(Math.round(x));
        
      float y = -3421.134f;
  
      // find the closest int for these floats
      System.out.println(Math.round(y));  
        
      double positiveInfinity = Double.POSITIVE_INFINITY;
  
      // returns the Integer.MAX_VALUE value when 
      System.out.println(Math.round(positiveInfinity));  
        
    }
}

chevron_right


Output:

4568
-3421
9223372036854775807


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.