Java ceil() method with Examples



The java.lang.Math.ceil() returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. Special cases −

  • If the argument value is already equal to a mathematical integer, then the result is the same as the argument.

  • If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.

  • If the argument value is less than zero but greater than -1.0, then the result is negative zero.

Example

Following is an example to implement the ceil() method in Java −

import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      // get two double numbers
      double x = 125.9;
      double y = 0.4873;
      // call ceal for these these numbers
      System.out.println("Math.ceil(" + x + ")=" + Math.ceil(x));
      System.out.println("Math.ceil(" + y + ")=" + Math.ceil(y));
      System.out.println("Math.ceil(-0.65)=" + Math.ceil(-0.65));
   }
}

Output

Math.ceil(125.9)=126.0
Math.ceil(0.4873)=1.0
Math.ceil(-0.65)=-0.0

Example

Let us see another example with negative input values −

Import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      // get two double numbers
      double x = 0.20;
      double y = -2.4;
      // call ceal for these these numbers
      System.out.println("Math.ceil(" + x + ")=" + Math.ceil(x));
      System.out.println("Math.ceil(" + y + ")=" + Math.ceil(y));
   }
}

Output

Math.ceil(0.2)=1.0
Math.ceil(-2.4)=-2.0

Advertisements