You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中Math.round(VALUE)与(int) VALUE的区别详解(Python转Java开发者)

Java中Math.round(VALUE)与(int)强制类型转换的区别

核心逻辑差异

  • (int)强制转换:直接丢弃小数部分,只保留整数位,和你熟悉的Python int(VALUE)行为完全一致。例子:
    • (int)2.9 → 2
    • (int)-2.9 → -2
  • Math.round(VALUE):执行四舍五入,将数值近似到最近的整数。如果小数部分恰好是0.5,会向正无穷方向取整。例子:
    • Math.round(2.9) → 3
    • Math.round(2.5) → 3
    • Math.round(-2.9) → -3
    • Math.round(-2.5) → -2

返回值类型区别

  • (int)强制转换的结果直接是int类型。
  • Math.round()的返回值分两种情况:传入float时返回int,传入double时返回long,如果需要int类型得手动强转,比如(int)Math.round(2.9)。

代码示例对比

public class RoundTest {
    public static void main(String[] args) {
        double posNum = 2.9;
        double posHalf = 2.5;
        double negNum = -2.9;
        double negHalf = -2.5;

        // 强制转换输出
        System.out.println("(int)2.9 = " + (int)posNum); // 2
        System.out.println("(int)-2.9 = " + (int)negNum); // -2

        // Math.round输出
        System.out.println("Math.round(2.9) = " + Math.round(posNum)); // 3
        System.out.println("Math.round(2.5) = " + Math.round(posHalf)); // 3
        System.out.println("Math.round(-2.9) = " + Math.round(negNum)); // -3
        System.out.println("Math.round(-2.5) = " + Math.round(negHalf)); // -2
    }
}

和Python操作的对应关系

Java的(int)强制转换完全对应Python的int(VALUE),都是截断小数。而Python中类似Math.round()的四舍五入是round(VALUE),但注意两者在0.5的处理上有差异:Python的round(2.5)返回2、round(-2.5)返回-2(向偶数取整),Java则是向正无穷取整。

内容的提问来源于stack exchange,提问作者AFT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 03:27:16