方法定义

public static double floor(double a)
  • 功能:返回小于或等于参数的最大整数(向下取整)
  • 参数double 类型数值
  • 返回double 类型的整数值(数学上的整数,但以浮点数形式存储)

功能说明

  1. 正数处理:直接舍弃小数部分
    Math.floor(3.7)  // = 3.0
    Math.floor(5.0)  // = 5.0
    
  2. 负数处理:向更小的整数方向取整
    Math.floor(-2.3)  // = -3.0
    Math.floor(-4.0)  // = -4.0
    
  3. 特殊值处理
    • NaN → 返回 NaN
    • 正无穷大 → 返回正无穷大
    • 负无穷大 → 返回负无穷大
    • -0.0 → 返回 -0.0

示例代码

public class FloorExample {
    public static void main(String[] args) {
        // 基本用法
        System.out.println(Math.floor(4.9));    // 4.0
        System.out.println(Math.floor(-4.9));   // -5.0
        
        // 边界值
        System.out.println(Math.floor(Double.MAX_VALUE)); // 最大值本身(已是整数)
        System.out.println(Math.floor(Double.MIN_VALUE)); // 0.0(接近0的正数)
        
        // 特殊值
        System.out.println(Math.floor(Double.NaN));        // NaN
        System.out.println(Math.floor(Double.POSITIVE_INFINITY)); // Infinity
        System.out.println(Math.floor(-0.0));             // -0.0
    }
}

使用技巧

  1. 整数转换:需显式转换为整型

    double num = 7.8;
    int result = (int) Math.floor(num); // result = 7
    
  2. 金额/单位计算:计算完整包装数量

    int itemsPerBox = 10;
    double totalItems = 54;
    int boxesNeeded = (int) Math.floor(totalItems / itemsPerBox); // 5
    
  3. 坐标处理:获取网格位置

    double playerX = 12.7;
    int gridX = (int) Math.floor(playerX); // 网格列=12
    

常见错误与注意事项

  1. 返回类型误解

    // 错误:期望得到int但实际返回double
    int a = Math.floor(3.8); // 编译错误!
    
    // 正确:显式转换
    int a = (int) Math.floor(3.8);
    
  2. 负数取整误解

    // 错误:期望-2实际得到-3
    double result = Math.floor(-2.7); // = -3.0
    
  3. 浮点精度问题

    // 由于浮点误差,0.1+0.1+0.1 ≠ 0.3
    double sum = 0.1 + 0.1 + 0.1; // ≈0.30000000000000004
    System.out.println(Math.floor(sum * 10)); // 期望3.0,实际2.0
    
  4. 大数处理问题

    // 超出long范围的数值
    double huge = 1e20;
    System.out.println(Math.floor(huge)); // 正常
    System.out.println((long) Math.floor(huge)); // 溢出
    

最佳实践与性能优化

  1. 整数判断优化

    // 代替:if (x == Math.floor(x))
    if (x % 1 == 0) { 
      // 是整数
    }
    
  2. 大数处理方案

    double bigValue = 9e18;
    // 使用BigDecimal处理超大数
    BigDecimal bd = new BigDecimal(bigValue);
    BigDecimal floored = bd.setScale(0, RoundingMode.FLOOR);
    
  3. 批量处理优化

    // 避免在循环中重复计算相同值
    double base = Math.floor(threshold);
    for (int i = 0; i < 1000000; i++) {
      // 使用base代替重复调用Math.floor
    }
    
  4. 替代方案选择

    // 需要整数结果时直接强转(正数场景)
    int fastFloor = (int) 7.9;  // =7(等效Math.floor正数部分)
    

总结

关键点 说明
核心功能 向下取整(正数截断小数,负数向更小方向取整)
返回类型 double 类型整数(需显式转换获取整型)
负数特性 Math.floor(-2.3) = -3.0(易错点!)
特殊值 正确处理 NaN/Infinity
精度风险 浮点计算误差可能导致意外结果
最佳实践 大数用 BigDecimal,循环外预计算,正数可考虑强转替代
性能 JVM 内联优化,单次调用约 1-3 纳秒(无需特别优化)

通过理解负数取整特性、正确处理返回类型转换、警惕浮点精度问题,并结合实际场景选择优化方案,可高效准确使用 Math.floor()