Java - Math.floor() Method



Description

The java.lang.Math.floor(double a) 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. Special cases −

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

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

Syntax

This method has the following syntax −

public static double floor(double a)

Parameters

Here is the detail of parameters −

  • A double primitive data type.

Return Value

  • This method returns the largest integer that is less than or equal to the argument. Returned as a double.

Example 1

In this example, we're showing the usage of Math.floor() method to get the largest double less than or equal to given double number. We've created two double variables d1, d2 and initialized them with negative and positive values. Then using Math.floor() method we're printing the required value of the given doubles.

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

      System.out.println(Math.floor(d1));
      System.out.println(Math.floor(d2)); 
   }
}

This will produce the following result −

Output

-101.0
100.0

Example 2

In this example, we're showing the usage of Math.floor() method to get the largest double less than or equal to given float number. We've created two float variables d1, d2 and initialized them with negative and positive values. Then using Math.floor() method we're printing the required value of the given floats.

public class Test { 
   public static void main(String args[]) {
      float d1 = (float) -100.675;
      float d2 = (float) 100.675;    

      System.out.println(Math.floor(d1));
      System.out.println(Math.floor(d2)); 
   }
}

This will produce the following result −

Output

-101.0
100.0

Example 3

In this example, we're showing the usage of Math.floor() method to check the case of 0. We've created one double and one float variables d1, d2 and initialized them with zero values. Then using Math.floor() method we're printing the required value of the given variables.

public class Test { 
   public static void main(String args[]) {
      float d1 = (float) 0.0;
      double d2 = 0.0;    

      System.out.println(Math.floor(d1));
      System.out.println(Math.floor(d2)); 
   }
}

This will produce the following result −

Output

0.0
0.0
java_numbers.htm
Advertisements