The Math ceil method example shows how to round up a number using the ceil method of the Java Math class. The ceil
method returns a number that is equal to or greater than the given number and is equal to an integer.
How to round up a number using the ceil method of the Math class?
We can use the ceil
method of the Java Math class to round up a number.
1 |
public static double ceil(double d) |
This method returns the smallest double number which is equal to or greater than the argument and is equal to an integer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.javacodeexamples.mathexamples; public class RoundUpNumberExample { public static void main(String[] args){ //returns 11.0 System.out.println( Math.ceil(10.2) ); //returns 11.0 System.out.println( Math.ceil(10.1) ); //returns 11.0 System.out.println( Math.ceil(10.9) ); //returns 11.0 System.out.println( Math.ceil(11) ); //returns 0.0 System.out.println( Math.ceil(0) ); //returns 0.0 System.out.println( Math.ceil(-0) ); //returns -21 System.out.println( Math.ceil(-21.2) ); } } |
Output
1 2 3 4 5 6 7 |
11.0 11.0 11.0 11.0 0.0 0.0 -21.0 |
Please note that the Math.ceil(-21.2) method returns -21.0 not -22.0. That is because -21 is greater than -21.2.
Please also note that the ceil
method returns a double. You may need to cast it to an appropriate data type from the double value.
Consider below given example.
1 2 3 4 |
int a = 9; int b = 2; System.out.println( Math.ceil(a/b) ); |
Output
1 |
4.0 |
Not what we expected. Dividing 9 by 2 equals 4.5 and rounding it up should give us 5.0 as a result. Instead, the result is 4.0. That is because a and b both are integers and dividing an integer with another integer always rounds the result which is 4.0. Getting ceil of 4.0 returns 4.0.
One way to fix it is to cast the division operation to a double value as given below
1 2 3 4 |
int a = 9; int b = 2; System.out.println( Math.ceil((double)a/b ) ); |
Output
1 |
5.0 |
This example is a part of the Java Math class tutorial with examples.
Please let me know your views in the comments section below.