对浮点数进行运算时,Java中使用了哪种舍入方法?

Which rounding method is used in Java when operating on floating point numbers?

语言是Java,机器是一台配备英特尔处理器的普通个人电脑。类型为double。

浮点数不能准确表示每个小数,除法或减法等运算的结果会以某种方式四舍五入为接近浮点数的表示形式。

我在问是否使用的舍入策略是:

  1. 从零开始舍入
  2. 四舍五入为零
  3. 向负无穷大舍入
  4. 向正无穷大舍入
  5. 四舍五入到最接近的值(上半部分)
  6. 四舍五入到最接近的值(向下一半)
  7. 四舍五入到最接近的值(偶数的一半)

Java Virtual Machine Floating-Point Arithmetic and IEEE 754

...

  • The rounding operations of the Java Virtual Machine always use IEEE 754 round to nearest mode. Inexact results are rounded to the nearest representable value, with ties going to the value with a zero least-significant bit. This is the IEEE 754 default mode. But Java Virtual Machine instructions that convert values of floating-point types to values of integral types round toward zero. The Java Virtual Machine does not give any means to change the floating-point rounding mode.

因此,正如 Patricia Shanahan 已经在评论中回答的那样,JVM 的舍入模式固定为 #7 舍入到您列表中最接近的(偶数的一半)。但是,这仅适用于浮点到浮点舍入。浮点数到整数的舍入使用 #2 向零舍入