Thursday 16 June 2022

Java math: floor: get largest double value that is less than or equal to this number

Java math ‘floor’ method Returns the largest double value that is less than or equal to the argument and is equal to a mathematical integer.

 

Signature

public static double floor(double a)

 

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.

 

Find the below working application.

 

FloorMethodDemo.java

package miscellaneous;

public class FloorMethodDemo {

	public static void main(String[] args) {
		double d1 = 10.9;
		double d2 = -10.9;

		System.out.printf("floor(%f) is %f\n", d1, Math.floor(d1));
		System.out.printf("floor(%f) is %f\n", d2, Math.floor(d2));

		// If the argument value is already equal to a mathematical integer, then the
		// result is the same as the argument.
		double d3 = 10;
		double d4 = -10;
		System.out.printf("floor(%f) is %f\n", d3, Math.floor(d3));
		System.out.printf("floor(%f) is %f\n", d4, Math.floor(d4));

		// If the argument is NaN or an infinity or positive zero or negative zero, then
		// the result is the same as the argument.
		System.out.printf("floor(%f) is %f\n", Double.NaN, Math.floor(Double.NaN));
		System.out.printf("floor(%f) is %f\n", Double.POSITIVE_INFINITY, Math.floor(Double.POSITIVE_INFINITY));
		System.out.printf("floor(%f) is %f\n", Double.NEGATIVE_INFINITY, Math.floor(Double.NEGATIVE_INFINITY));
		System.out.printf("floor(%f) is %f\n", 0.0, Math.floor(0.0));
		System.out.printf("floor(%f) is %f\n", -0.0, Math.floor(-0.0));
	}

}

 

Output

floor(10.900000) is 10.000000
floor(-10.900000) is -11.000000
floor(10.000000) is 10.000000
floor(-10.000000) is -10.000000
floor(NaN) is NaN
floor(Infinity) is Infinity
floor(-Infinity) is -Infinity
floor(0.000000) is 0.000000
floor(-0.000000) is -0.000000

 

 

 

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment