Close

Java - Math.ceil() Examples

Java Java API 


Class:

java.lang.Math

java.lang.Objectjava.lang.Objectjava.lang.Mathjava.lang.MathLogicBig

Method:

public static double ceil(double a)

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.


Examples


package com.logicbig.example.math;

import java.util.ArrayList;
import java.util.List;

public class CeilExample {

public static void main(String... args) {
List<Double> list = new ArrayList<>();
list.add(17.979);
list.add(21.1);
list.add(21.5);
list.add(-19.95);
list.add(-19.4);
list.add(-0.1);
list.add(+0.1);

for (double value : list) {
String sign = value > 0 ? "positive" : "negative";
Double CeilValue = Math.ceil(value);
System.out.printf("The ceil of %s number %6s = %5.2f%n", sign, value, CeilValue);
}
}
}

Output

The ceil of positive number 17.979 = 18.00
The ceil of positive number 21.1 = 22.00
The ceil of positive number 21.5 = 22.00
The ceil of negative number -19.95 = -19.00
The ceil of negative number -19.4 = -19.00
The ceil of negative number -0.1 = -0.00
The ceil of positive number 0.1 = 1.00




How to use Math.ceil() to round a number up to n decimal places?

package com.logicbig.example.math;

public class CeilExample2 {

public static void main(String... args) {
roundUp(115.9711123, 3);
roundUp(91.1236234, 2);
roundUp(-139.5114223, 5);
roundUp(-0.1998234, 4);
}

private static void roundUp(double value, int decimalPlaces) {
int temp = (int) Math.pow(10, decimalPlaces);
double roundedValue = Math.ceil(value * temp) / temp;
System.out.printf("Rounding up %12s to %s decimal places = %s%n", value, decimalPlaces, roundedValue);
}
}

Output

Rounding up  115.9711123 to 3 decimal places = 115.972
Rounding up 91.1236234 to 2 decimal places = 91.13
Rounding up -139.5114223 to 5 decimal places = -139.51142
Rounding up -0.1998234 to 4 decimal places = -0.1998




See Also