温馨提示×

Java round函数的四舍五入规则是什么

小樊
142
2024-08-27 06:34:03
栏目: 编程语言

Java中的round()函数使用的是四舍五入(Round half up)规则。这意味着当一个数字恰好位于两个可能结果的中间时,它会向最接近的偶数方向舍入。例如:

  • 对于正数,如果小数部分等于或大于0.5,那么它将向上舍入;如果小数部分小于0.5,那么它将向下舍入。
  • 对于负数,如果小数部分等于或大于0.5,那么它将向下舍入;如果小数部分小于0.5,那么它将向上舍入。

这种舍入方式有助于减少在多次舍入操作中的误差累积。

以下是一些示例:

System.out.println(Math.round(11.5)); // 输出 12
System.out.println(Math.round(10.5)); // 输出 11
System.out.println(Math.round(10.4)); // 输出 10
System.out.println(Math.round(-11.5)); // 输出 -12
System.out.println(Math.round(-10.5)); // 输出 -11
System.out.println(Math.round(-10.4)); // 输出 -10

需要注意的是,round()函数返回的是一个长整型(long)值,如果你需要得到一个浮点数结果,可以使用Math.rint()函数。

0