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.
class GFG {
public static void main(String[] args) {
double num = 2.3;
System.out.println(Math.ceil(num));
}
}
Output
3.0
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.
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 = -0.12;
System.out.println(Math.ceil(a));
System.out.println(Math.ceil(b));
System.out.println(Math.ceil(c));
System.out.println(Math.ceil(d));
System.out.println(Math.ceil(e));
}
}
Output
5.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.
class GFG {
public static void main(String[] args) {
double number = 3.5;
double result = Math.ceil(number);
System.out.println(result);
}
}
Output :
4.0Explanation:
- A decimal value 3.5 is stored in the variable number.
- The Math.ceil() method is called with number as the argument.
- The method rounds the value upward to the nearest integer.
- The result is returned as a double (4.0).