The Math.ceil() method in Java is used to return the smallest integer value that is greater than or equal to a given number. The returned value is of type double and represents the mathematical ceiling of the argument. This method belongs to the java.lang.Math class.
Explanation:
- A decimal value 2.3 is stored in the variable num.
- The Math.ceil() method is called with num as the argument.
- The method rounds the value up to the nearest integer.
- The result is returned as a double value (3.0).
Syntax:
public static double ceil(double a)
- Parameter: "a" the double value whose ceiling is to be determined.
- Return Value: Returns the nearest integer value (as double) that is greater 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.
- If the argument is less than 0 but greater than -1.0, the result is negative zero (-0.0).
Example 1: This program demonstrates how the Math.ceil() method works with different types of double values in Java.
Output5.0
Infinity
0.0
-0.0
-0.0
Explanation:
- The Math class is used to access the ceil() method.
- Variable a holds a positive decimal value, which is rounded up to the next integer.
- Variable b represents positive infinity, so the result remains infinity.
- Variable c is positive zero, and the output remains 0.0.
- Variable d is negative zero, and the output remains -0.0.
- Variable e is a negative value between -1.0 and 0.0, so the result is -0.0.
- Each result is printed to show how Math.ceil() behaves in different cases.
Example 2: This program shows how the Math.ceil() method rounds a decimal number up to the nearest integer value.