Last Updated : 13 May, 2025
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:
These special cases make sure that the Math.round() methods work correctly.
Syntax of round() Methodpublic static long round(float val)
Now, we are going to discuss some examples for better understanding and clarity.
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));
}
}
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));
}
}
4568 -3421 9223372036854775807
Explanation: When the input is Double.POSITIVE_INFINITY, Math.round() returns Long.MAX_VALUE, which is 9223372036854775807.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4