Java math ceil function is used to get smallest integer which is greater than number.
Real life example
Let’s say a telephone company charges you 1 dollar per minute. When you talk to someone for 1 minute 5 seconds, it will still charge you 2 dollar for that call. So telephone company can use Math.ceil function to get 2 minutes from 1 minutes 5 seconds.
Syntax
public static double ceil(double x)
Example
Let’s use math’s ceil function in the example.
package org.arpit.java2blog;
public class MathCeilMain {
public static void main(String[] args) {
// Use math.ceil to get smaller integer greater
// than number
System.out.println("Ceil value for 2.6 = " + Math.ceil(2.6));
System.out.println("Ceil value for 26.1 = " + Math.ceil(26.1));
System.out.println("Ceil value for -0.8 = " + Math.ceil(-0.8));
System.out.println("Ceil value for -6.2 = " + Math.ceil(-6.2));
float f=4.6f;
System.out.println("Ceil value for 4.6f = " + Math.ceil(f));
}
}
When you run above program, output of the program will be:
Ceil value for 2.6 = 3.0
Ceil value for 26.1 = 27.0
Ceil value for -0.8 = -0.0
Ceil value for -6.2 = -6.0
Ceil value for 4.6f = 5.0
Ceil value for 26.1 = 27.0
Ceil value for -0.8 = -0.0
Ceil value for -6.2 = -6.0
Ceil value for 4.6f = 5.0
Few points about Math.ceil function:
- In case of Nan or infinity or zero, it will give you same result as argument.
- If you pass a value which is already equal to integer, it will result in same value.
That’s all about Java math ceil function.