Math.floor() returns the largest whole number that is less than or equal to the value you pass. In simple words, it always rounds down, towards negative infinity. It returns a double.
public static double floor(double a)
Basic Example
public class FloorDemo {
public static void main(String[] args) {
System.out.println(Math.floor(4.8));
System.out.println(Math.floor(23.99));
System.out.println(Math.floor(7.0));
System.out.println(Math.floor(-4.2));
System.out.println(Math.floor(-23.99));
}
}
Output:
4.0
23.0
7.0
-5.0
-24.0
For positive numbers, floor() simply drops the decimal part. For negative numbers it moves further away from zero: the floor of -4.2 is -5.0, because -5 is the largest whole number that is still less than -4.2.
floor() vs ceil() vs round() vs (int)
| Value | Math.floor |
Math.ceil |
Math.round |
(int) cast |
|---|---|---|---|---|
| 4.8 | 4.0 | 5.0 | 5 | 4 |
| 4.2 | 4.0 | 5.0 | 4 | 4 |
| -4.2 | -5.0 | -4.0 | -4 | -4 |
| -4.8 | -5.0 | -4.0 | -5 | -4 |
The (int) cast truncates towards zero, which is different from floor() for negative numbers. Mixing them up is a common source of bugs.
Getting an int Instead of a double
double price = 199.75;
int rupees = (int) Math.floor(price);
System.out.println(rupees);
Output:
199
Practical Example: Minutes to Hours and Minutes
int totalMinutes = 157;
int hours = (int) Math.floor(totalMinutes / 60.0);
int minutes = totalMinutes % 60;
System.out.println(hours + " h " + minutes + " min");
Output:
2 h 37 min
The Integer Division Trap
System.out.println(Math.floor(10 / 3)); // 10 / 3 is int division = 3
System.out.println(Math.floor(-7 / 2)); // -7 / 2 is int division = -3
System.out.println(Math.floorDiv(-7, 2)); // true floor division
Output:
3.0
-3.0
-4
When both numbers are integers, Java divides first (truncating towards zero) and then passes the result to floor(). So Math.floor(-7 / 2) gives -3.0, not -4.0. Use -7 / 2.0, or Math.floorDiv() for integers.
Special Cases
- If the argument is already a whole number, the same value is returned (as a double).
Math.floor(Double.NaN)returnsNaN, and infinity stays infinity.Math.floor(-0.5)returns-1.0.
Frequently Asked Questions
What does Math.floor() return in Java?
A double holding the largest whole number less than or equal to the argument.
What is Math.floor(-2.5)?
-3.0, because floor always rounds down.
How is Math.floor() different from casting to int?
Casting truncates towards zero, so (int) -2.5 is -2, while Math.floor(-2.5) is -3.0.
Related: Java Math class · Arithmetic operators in Java