Math.floor() Method in Java

Math.floor() Method in Java | The floor() method of java.lang.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.

Method prototype of the java.lang.Math.floor(),
public static double floor(double a)

Java Math.floor() Examples

public class Test{
   public static void main(String[] args) {
      System.out.println(Math.floor(2.0)); // 2.0
      System.out.println(Math.floor(-2.0)); // -2.0

      System.out.println(Math.floor(2.5)); // 2.0
      System.out.println(Math.floor(-2.5)); // -3.0

      System.out.println(Math.floor(2.9)); // 2.0
      System.out.println(Math.floor(-2.9)); // -3.0
   }
}

If we import Math class statically and then we can invoke floor() method without calling through it’s class name.

import static java.lang.Math.*;
public class Test {
   public static void main(String[] args) {
      System.out.println(floor(9.9)); // 9.0
      System.out.println(floor(5.0)); // 5.0
   }
}

The “import static java.lang.Math.*;” statement will import all static members of the Math class. But if we want to import only the floor() method of the Math class, not another static method and variables of Math class then we can use the “import static java.lang.Math.floor;” statement. Learn more about static import in Java

import static java.lang.Math.floor;
public class Test {
   public static void main(String[] args) {
      System.out.println(floor(9.9)); // 9.0
      System.out.println(floor(5.0)); // 5.0
   }
}

More Examples,

When the argument is positive

Math.floor(2.0)2.0
Math.floor(2.1)2.0
Math.floor(2.5)2.0
Math.floor(2.9)2.0
Math.floor(3.0)3.0
Math.floor(3.3)3.0
Math.floor(3.5)3.0
Math.floor(3.9)3.0

When the argument is negative

Math.floor(-2.0)-2.0
Math.floor(-2.1)-3.0
Math.floor(-2.5)-3.0
Math.floor(-2.9)-3.0
Math.floor(-3.0)-3.0
Math.floor(-3.3)-4.0
Math.floor(-3.5)-4.0
Math.floor(-3.9)-4.0

Special Cases for Math.floor() Method in Java

1) If passed values an integer then the same value is returned.

Math.floor(5) => 5.0
Math.floor(6.0) => 6.0

2) If the argument is zero (either positive or negative), infinity or NaN then also the same value is returned.

// argument is zero
Math.floor(0) => 0.0
Math.floor(-0) => 0.0

// argument is INFINITY
Math.floor(Double.POSITIVE_INFINITY) => Infinity
Math.floor(Double.NEGATIVE_INFINITY) => -Infinity

// argument is NaN
Math.floor(Double.NaN) => NaN

Note:- the value of Math.ceil(x) is exactly the value of -Math.floor(-x).

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *