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.
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.
Output4.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.