Java floor() method with Examples

Java 8Object Oriented ProgrammingProgramming

The java.lang.Math.floor() 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.

Let us now see an example to implement the floor() method in Java −

Example

import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      // get two double numbers
      double x = 60984.1;
      double y = -497.99;
      // call floor and print the result
      System.out.println("Math.floor(" + x + ")=" + Math.floor(x));
      System.out.println("Math.floor(" + y + ")=" + Math.floor(y));
      System.out.println("Math.floor(0)=" + Math.floor(0));
   }
}

Output

Math.floor(60984.1)=60984.0
Math.floor(-497.99)=-498.0
Math.floor(0)=0.0

Example

Let us now see another example wherein we will be checking for negative and other values −

import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      // get two double numbers
      double x = 0.0;
      double y = -5.7;
      double z = 1.0/0;
      // call floor and print the result
      System.out.println("Math.floor(" + x + ")=" + Math.floor(x));
      System.out.println("Math.floor(" + y + ")=" + Math.floor(y));
      System.out.println("Math.floor(" + z + ")=" + Math.floor(z));
   }
}

Output

Math.floor(0.0)=0.0
Math.floor(-5.7)=-6.0
Math.floor(Infinity)=Infinity
raja
Published on 24-Sep-2019 08:39:19
Advertisements