The Math.floor() method in Java returns the largest integer value that is less than or equal to a given number. The result is returned as a double and represents the mathematical floor of the argument. This method is part of the java.lang.Math class.
class GFG {
public static void main(String[] args) {
double num = 2.7;
System.out.println(Math.floor(num));
}
}
Output
2.0
Explanation:
- A decimal value 2.7 is stored in the variable num.
- Math.floor(num) rounds the value downward to the nearest integer.
- The result is returned as a double (2.0).
Syntax
public static double floor(double a)
- Parameter: "a" the double value whose floor is to be determined.
- Return Value: Returns the nearest integer value (as double) that is less than or equal to the given argument.
Special Cases
- If the argument is already an integer, the same value is returned.
- If the argument is NaN, positive infinity, negative infinity, positive zero, or negative zero, the result is the same as the argument.
- Negative numbers between -1.0 and 0.0 are floored to -1.0.
Example 1: This program demonstrates how the Math.floor() method rounds different types of double values down to the nearest integer in Java.
import java.lang.Math;
class GFG {
public static void main(String args[]) {
double a = 4.3;
double b = 1.0 / 0;
double c = 0.0;
double d = -0.0;
double e = -2.3;
System.out.println(Math.floor(a));
System.out.println(Math.floor(b));
System.out.println(Math.floor(c));
System.out.println(Math.floor(d));
System.out.println(Math.floor(e));
}
}
Output
4.0 Infinity 0.0 -0.0 -3.0
Explanation:
- The Math class is used to access the floor() method.
- Variable a = 4.3 is a positive decimal; Math.floor(a) rounds it down to 4.0.
- Variable b = 1.0 / 0 represents positive infinity, and Math.floor(b) returns Infinity.
- Variable c = 0.0 is positive zero, and the output remains 0.0.
- Variable d = -0.0 is negative zero, and the output remains -0.0.
- Variable e = -2.3 is a negative decimal; Math.floor(e) rounds it down to -3.0.
- Each result is printed to demonstrate how Math.floor() behaves for different input values.
Example 2: This program shows how the Math.floor() method rounds a positive decimal number down to the nearest integer in Java.
class GFG {
public static void main(String[] args) {
double number = 3.5;
double result = Math.floor(number);
System.out.println(result);
}
}
Output :Â
3.0Explanation:
- A decimal value 3.5 is stored in the variable number.
- The Math.floor(number) method rounds the value downward to the nearest integer.
- The result is returned as a double (3.0).