Math.ceil Java Example
1. Introduction
In this example, we will learn about the Math.ceil Java method. Java math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions. Some of the most important of Math class methods are min(), max(), avg(), sin(), cos(). You could take a look at all methods of Math class in the java doc.
But today we will be familiar with the ceil method of Math class.
2. What is the ceil method?
Math.ceil method always rounds a number up to the next largest double or in other words returns the smallest double value that is greater than or equal to the argument. For example:
System.out.println(Math.ceil(1.2));
// expected result: 2.0
System.out.println(Math.ceil(2.0001));
// expected result: 3.0
System.out.println(Math.ceil(-2.01));
// expected result: -2.0
3. Method signature
The following snippet shows the syntax of Math.ceil method.
public static double ceil(double a)
4. Special Cases
- If the input is an infinity then the result is infinity.
- If the input is a positive zero then the result is a positive zero.
- If the input is negative zero then the result is negative zero.
- If the input is less than zero but greater than -1 then the result is negative zero.
5. Math.ceil in Java – Samples
public class CeilExample { public static void main(String[] args) { // Integer number System.out.println(Math.ceil(2)); System.out.println(Math.ceil(1.2)); System.out.println(Math.ceil(2.001)); // Infinity example System.out.println(Math.ceil(1.0/0)); // Positive zero System.out.println(Math.ceil(0)); // Negative zero System.out.println(Math.ceil(-0.0)); // Negative number less than zero but greater than -1 System.out.println(Math.ceil(-0.001)); // Negative number System.out.println(Math.ceil(-1.02)); } }
After running the above code in any IDE of your choice you’ll receive the following output:
2.0
2.0
3.0
Infinity
0.0
-0.0
-0.0
-1.0
6. Summary
In this article we reviewed the ceil() method from java.lang.Math class. Math.ceil method always rounds a number up to the next largest double.
7. Download the source code
That was a Math.ceil Java Example.
You can download the full source code of this example here: Math.ceil Java Example