Java - Math.ceil() Method



Description

The method ceil gives the smallest double that is greater than or equal to the argument. Following are the special cases to consider −

  • Case 1 − argument value is already equal to a mathematical integer, then the result is the same as the given argument.

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

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

Syntax

This method has the following syntax −

public static double ceil(double a)

Parameters

Here is the detail of parameters −

  • A double primitive data type.

Return Value

  • This method returns the smallest integer that is greater than or equal to the argument. Returned as a double.

Example 1

In this example, we're showing the usage of Math.ceil() method to get the smallest integer greater than or equal to given double number. We've created two double variables d1, d2 and initialized them with negative and positive values. Then using Math.ceil() method we're printing the required value of the given doubles.

public class Test { 
   public static void main(String args[]) {
      double d1 = -100.675;
      double d2 = 100.675;    

      System.out.println(Math.ceil(d1));
      System.out.println(Math.ceil(d2)); 
   }
}

This will produce the following result −

Output

-100.0
101.0

Example 2

In this example, we're showing the usage of Math.ceil() method to get the smallest integer greater than or equal to given float number. We've created two float variables d1, d2 and initialized them with negative and positive values. Then using Math.ceil() method we're printing the required value of the given floats.

public class Test { 
   public static void main(String args[]) {
      float d1 = (float) -100.675;
      float d2 = (float) 100.675;    

      System.out.println(Math.ceil(d1));
      System.out.println(Math.ceil(d2)); 
   }
}

This will produce the following result −

Output

-100.0
101.0

Example 3

In this example, we're showing the usage of Math.ceil() method to check the case of 0. We've created one double and one float variables d1, d2 and initialized them with zero values. Then using Math.ceil() method we're printing the required value of the given variables.

public class Test { 
   public static void main(String args[]) {
      float d1 = (float) 0.0;
      double d2 = 0.0;    

      System.out.println(Math.ceil(d1));
      System.out.println(Math.ceil(d2)); 
   }
}

This will produce the following result −

Output

0.0
0.0
java_numbers.htm
Advertisements