一、方法定义

Math.round() 是 Java 标准库 java.lang.Math 类中的一个静态方法,用于将浮点数(floatdouble)四舍五入为最接近的整数值。

方法签名:

public static long round(double a)
public static int round(float a)
  • 参数
    • a:要四舍五入的 doublefloat 值。
  • 返回值
    • 对于 double:返回 long 类型。
    • 对于 float:返回 int 类型。

二、功能说明

Math.round() 实现的是 “四舍五入到最近的整数” 的数学规则。其内部实现原理如下:

  • 对于 double 类型:Math.round(a) 等价于 (long)Math.floor(a + 0.5d)
  • 对于 float 类型:Math.round(a) 等价于 (int)Math.floor(a + 0.5f)

⚠️ 特别注意:当数值正好处于两个整数中间(如 2.5)时,向正无穷方向舍入(即向上取整),这与某些数学定义中的“银行家舍入”不同。


三、示例代码

基本用法:

public class MathRoundExample {
    public static void main(String[] args) {
        // 正数测试
        System.out.println(Math.round(3.2));  // 输出: 3
        System.out.println(Math.round(3.5));  // 输出: 4
        System.out.println(Math.round(3.7));  // 输出: 4

        // 负数测试
        System.out.println(Math.round(-3.2)); // 输出: -3
        System.out.println(Math.round(-3.5)); // 输出: -3 (关键!)
        System.out.println(Math.round(-3.7)); // 输出: -4

        // float 类型
        float f = 2.6f;
        System.out.println(Math.round(f));    // 输出: 3
    }
}

输出结果:

3
4
4
-3
-3
-4
3

🔍 注意:-3.5 四舍五入为 -3,因为 Math.round(-3.5) = (long)Math.floor(-3.5 + 0.5) = (long)Math.floor(-3.0) = -3


四、使用技巧

1. 保留小数位的“伪四舍五入”

若要保留 n 位小数并四舍五入,可结合乘除法:

double value = 3.14159;
int scale = 2;
double rounded = Math.round(value * Math.pow(10, scale)) / Math.pow(10, scale);
System.out.println(rounded); // 输出: 3.14

✅ 推荐使用 BigDecimal 实现精确小数控制(见注意事项)。

2. 类型转换注意

Math.round(double) 返回 long,需注意赋值给 int 可能溢出:

double d = 3_000_000_000.0;
long l = Math.round(d); // OK
// int i = Math.round(d); // 编译错误!可能溢出

五、常见错误

❌ 错误1:误认为 -3.5 四舍五入为 -4

System.out.println(Math.round(-3.5)); // 实际输出 -3,不是 -4

原因:-3.5 + 0.5 = -3.0floor(-3.0) = -3

❌ 错误2:忽略返回类型,导致类型不匹配

int result = Math.round(5.7); // 编译错误!返回 long

✅ 正确写法:

long result = Math.round(5.7);
// 或强制转换(确保不溢出)
int result = (int) Math.round(5.7);

❌ 错误3:对大浮点数使用 round(float) 导致精度丢失

float big = 1e9f + 0.6f;
System.out.println(Math.round(big)); // 可能不是预期值(float 精度有限)

六、注意事项

项目 说明
负数中点处理 -3.5-3,不是 -4
返回类型差异 doublelongfloatint
精度问题 float 类型本身精度有限,不适用于高精度计算
边界值 接近 Long.MAX_VALUEdouble 四舍五入可能溢出
NaN 和无穷大 Math.round(Double.NaN)0Math.round(Double.POSITIVE_INFINITY)Long.MAX_VALUE

七、最佳实践

  1. 明确需求:若需精确小数控制(如金融计算),使用 BigDecimal 配合 RoundingMode

    BigDecimal bd = new BigDecimal("3.145");
    bd = bd.setScale(2, RoundingMode.HALF_UP); // 3.15
    
  2. 类型安全:避免强制转换导致溢出,使用 long 接收 doubleround 结果。

  3. 负数处理:理解 Math.round() 对负数的“向正无穷”舍入行为。

  4. 性能敏感场景Math.round() 是本地方法(native),性能优异,适合高频调用。


八、性能优化建议

场景 建议
高频调用 Math.round() 性能优秀,无需优化
批量处理 可考虑使用 Arrays 或流式处理,减少方法调用开销
替代方案 若只需整数部分,用 (int) 强制转换更快(但非四舍五入)
避免重复计算 Math.pow(10, n) 可缓存

九、总结

项目 内容
核心功能 将浮点数四舍五入为最接近的整数
关键特性 负数中点(如 -3.5)向正无穷方向舍入
返回类型 doublelongfloatint
适用场景 一般整数舍入、性能要求高的计算
慎用场景 高精度小数、金融计算(应使用 BigDecimal
最佳实践 理解行为、注意类型、避免溢出、精度敏感用 BigDecimal

一句话掌握
Math.round(x) = (long) Math.floor(x + 0.5),对正负中点都向正无穷方向舍入。