java - 将 double 向下转型为 int 哪种舍入模式?

标签 java rounding downcast

下面哪种舍入模式会将 double 类型转换为 int 类型?

使用给定的 rounding mode 将输入四舍五入到一位数字的结果

Input                                                   HALF_EVEN
Number  UP      DOWN    CEILING FLOOR   HALF_UP HALF_DOWN       UNNECESSARY
5.5     6       5       6       5       6       5       6       throw ArithmeticException
2.5     3       2       3       2       3       2       2       throw ArithmeticException
1.6     2       1       2       1       2       2       2       throw ArithmeticException
1.1     2       1       2       1       1       1       1       throw ArithmeticException
1.0     1       1       1       1       1       1       1       1
-1.0    -1      -1      -1      -1      -1      -1      -1      -1
-1.1    -2      -1      -1      -2      -1      -1      -1      throw ArithmeticException
-1.6    -2      -1      -1      -2      -2      -2      -2      throw ArithmeticException
-2.5    -3      -2      -2      -3      -3      -2      -2      throw ArithmeticException
-5.5    -6      -5      -5      -6      -6      -5      -6      throw ArithmeticException

我知道它与我引用的枚举的原语转换无关,但是该表肯定涵盖了 double 向下转换为 int 的方式。列表中的哪一个是这样的? 提前致谢。

最佳答案

Which of the following rounding mode is followed by casting a double to an int?

它只是向零截断 - 由问题中名称容易混淆的 DOWN 表示。

来自section 5.1.3 of the JLS :

A narrowing conversion of a floating-point number to an integral type T takes two steps:

In the first step, the floating-point number is converted either to a long, if T is long, or to an int, if T is byte, short, char, or int, as follows:

  • If the floating-point number is NaN (§4.2.3), the result of the first step of the conversion is an int or long 0.

  • Otherwise, if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode (§4.2.3). Then there are two cases:

[ ... ]

(其余内容与问题无关。)

关于java - 将 double 向下转型为 int 哪种舍入模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18765393/

相关文章:

java - 数据驱动设计,引用数据

Eclipse 中的 java.lang.NoClassDefFoundError,但 Ant 中没有

java - 在 Java 中如何舍入到最接近的 20 的倍数?

uiimage - 从 AnyObject 向下转换为 UIImage[] - Swift

java - 如何将数组转换为不带逗号/括号的字符串格式并添加括号作为值

java - 使用 GUI 输出框四舍五入到不同的小数位

java - Scala 和 Java 中的 RoundingMode.HALF_UP 区别

c# - 使用继承的自定义 IDataReader 从 IDbCommand 读取

java - 使用快速排序对大型列表进行排序时总是会发生堆栈溢出