Open In App

Java Math round() Method

Last Updated : 13 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Math.round() method is a part of the java.lang.Math library. This method returns the closest long to the argument. In this article, we are going to discuss how this method works for regular values and for special cases.

Note: If the fraction is less than 0.5 then the number is rounded down and if the fraction is more than 0.5 then the number is rounded up.

Special Cases:

  • If the argument is NaN, the method will return zero.
  • If the argument is negative infinity or any value less than or equal to the value of an Long.MIN_VALUE, the method will return an Long.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to Long.MAX_VALUE, the method will return Long.MAX_VALUE.

These special cases make sure that the Math.round() methods work correctly.

Syntax of round() Method

public static long round(float val)

  • Parameter: This method takes a single parameter val of type float, which is a float that will be rounded to nearest integer.
  • Return Type: This method returns the closest rounded value as long.

Now, we are going to discuss some examples for better understanding and clarity.


Examples of Java Math round() Method

Example 1: In this example, we will see the basic usage of Math.round() method.

Java
// Java program to demonstrate the working
// of Math.round() method
import java.lang.Math;

class Geeks {
    
    // driver code
    public static void main(String args[]) {
        
        // float numbers
        float x = 4567.9874f;

        // find the closest long for these floats
        System.out.println(Math.round(x)); 
    }
}

Output
4568

Explanation: Here, we rounded the value of x to the nearest long.


Example 2: In this example, we will see how the round() method handles all the special cases.

Java
// Java program to demonstrate the working
// of Math.round() method for special cases
import java.lang.Math;

class Geeks {
    
    // driver code
    public static void main(String args[]) {
        
        // float numbers
        float x = 4567.9874f;

        // find the closest long for these floats
        System.out.println(Math.round(x));

        float y = -3421.134f;

        // find the closest long for these floats
        System.out.println(Math.round(y));

        double p = Double.POSITIVE_INFINITY;

        // returns the Long.MAX_VALUE value when 
        System.out.println(Math.round(p));
    }
}

Output
4568
-3421
9223372036854775807

Explanation: When the input is Double.POSITIVE_INFINITY, Math.round() returns Long.MAX_VALUE, which is 9223372036854775807.


Practice Tags :

Similar Reads