Java Math floor() example

In this guide, you will learn about the Math floor() method in Java programming and how to use it with an example.

1. Math floor() Method Overview


The floor() method of Java's Math class returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.




- a: A double value whose floor value is to be determined.

Key Points:

- If the argument is NaN, positive infinity, or negative infinity, then the result will be NaN, positive infinity, or negative infinity, respectively.

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

- The return type is double, even for whole number results.

2. Math floor() Method Example

public class FloorExample {
    public static void main(String[] args) {
        double[] values = {42.1, 42.7, -42.1, -42.7};

        for (double value : values) {
            // Calculate the floor value
            double floorValue = Math.floor(value);
            System.out.println("Floor value of " + value + ": " + floorValue);

        // Special case for NaN
        System.out.println("Floor value of NaN: " + Math.floor(Double.NaN));


Floor value of 42.1: 42.0
Floor value of 42.7: 42.0
Floor value of -42.1: -43.0
Floor value of -42.7: -43.0
Floor value of NaN: NaN


In the example:

1. For 42.1 and 42.7, their floor values are 42.0 because the method rounds down.

2. For negative numbers like -42.1 and -42.7, their floor values move further away from zero, resulting in -43.0.

3. The method returns NaN when passed NaN as an argument, aligning with the principle that operations with NaN generally yield NaN.

Related Java Math class method examples