CodeGym/Java 博客/China/Java floor() 方法

John Selawsky
Senior Java Developer and Tutor at LearningTree

# Java floor() 方法

## 数学中的向下取整函数是什么？

``````floor(5) = 5
floor (1.3) = 1
floor (7.9) = 7``````

## Java 中的 Math.floor() 方法是什么？

Java 提供了一个等价的数学向下取整函数。下面说明了你如何理解该方法。
Java 中的 Math.floor() 方法返回“double”值，该值小于和等于参数的最大整数。

## 方法头

``public static double floor(double x)``

## 示例

``````public class Driver1 {

public static void main(String[] args) {

double x = 50; // floor for whole number (Integer value)
double floorValue = Math.floor(x);
System.out.println("floor⌊" + x + "⌋ = " + floorValue);

x = 21.7; // floor for positive decimal
floorValue = Math.floor(x);
System.out.println("floor⌊" + x + "⌋ = " + floorValue);

x = -21.7; // floor for negative decimal
floorValue = Math.floor(x);
System.out.println("floor⌊" + x + "⌋ = " + floorValue);

x = 0; // floor for zero (Integer value)
floorValue = Math.floor(x);
System.out.println("floor⌊" + x + "⌋ = " + floorValue);

// Boundary Cases
x = +3.3/0;  // Case I - floor for +Infinity
floorValue = Math.floor(x);
System.out.println("floor⌊" + x + "⌋ = " + floorValue);

x = -3.3/0; // Case II - floor for -infinity
floorValue = Math.floor(x);
System.out.println("floor⌊" + x + "⌋ = " + floorValue);

x = -0.0/0; // Case III - floor for NaN
floorValue = Math.floor(x);
System.out.println("floor⌊" + x + "⌋ = " + floorValue);

}

}``````

### 输出

floor⌊50.0⌋ = 50.0 floor⌊21.7⌋ = 21.0 floor⌊-21.7⌋ = -22.0 floor⌊0.0⌋ = 0.0 floor⌊Infinity⌋ = Infinity floor⌊-Infinity⌋ = -Infinity floor⌊NaN⌋ = NaN