Sunday 5 June 2022

Java math ceil(): Get ceiling value of a number

Java math 'ceil' method takes a double value as an argument and return the smallest double value that is greater than or equal to the argument and is equal to a mathematical integer.

 

Signature

public static double ceil(double a)

 

Example

Math.ceil(4.1); // Return 5.0

Math.ceil(4.6); // Return 5.0

 

Special cases to consider

a. If the argument value is already equal to a mathematical integer, then the result is the same as the argument.

 

b. If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.

 

c. If the argument value is less than zero but greater than -1.0, then the result is negative zero.

 

 

Find the below working application.

 

CeilDemo.java

package com.sample.app;

public class CeilDemo {
	
	public static void main(String[] args) {
		double val1 = 4.1;
		double val2 = 4.6;
		
		System.out.printf("ceil(%f) is %f\n", val1, Math.ceil(val1));
		System.out.printf("ceil(%f) is %f\n", val2, Math.ceil(val2));
		
		// If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
		double val3 = 4.0;
		System.out.printf("ceil(%f) is %f\n", val3, Math.ceil(val3));
		
		// If the argument is NaN or an infinity or positive zero or negative zero, 
		// then the result is the same as the argument.
		double val4 = Double.NaN;
		double val5 = Double.POSITIVE_INFINITY;
		double val6 = Double.NEGATIVE_INFINITY;
		double val7 = 0.0;
		double val8 = -0.0;
		System.out.printf("ceil(%f) is %f\n", val4, Math.ceil(val4));
		System.out.printf("ceil(%f) is %f\n", val5, Math.ceil(val5));
		System.out.printf("ceil(%f) is %f\n", val6, Math.ceil(val6));
		System.out.printf("ceil(%f) is %f\n", val7, Math.ceil(val7));
		System.out.printf("ceil(%f) is %f\n", val8, Math.ceil(val8));
		
		double val9 = -0.4;
		System.out.printf("ceil(%f) is %f\n", val9, Math.ceil(val9));
	}

}

 

Output

ceil(4.100000) is 5.000000
ceil(4.600000) is 5.000000
ceil(4.000000) is 4.000000
ceil(NaN) is NaN
ceil(Infinity) is Infinity
ceil(-Infinity) is -Infinity
ceil(0.000000) is 0.000000
ceil(-0.000000) is -0.000000
ceil(-0.400000) is -0.000000

 

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment