## 如何用Java将Double类型转为Integer？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (10)
• 关注 (0)
• 查看 (259)

`"java.lang.ClassCastException: java.lang.Double incompatible with java.lang.Integer"`

### 10 个回答

`Double和Integer类型不一致`所以出错。注意`Double和`原始的`double也不同，Dounle是一个Number`型，所以它存在方法`intValue`，你可以使用它获得`int类型的值`

```Double d = 13.5578;
int i = d.intValue();
System.out.println(i);```

```Double d = 100.00;
Integer i = d.intValue();```

`Integer i = new Integer(d.intValue());`

```double a = 13.34;
int b = (int) a;

System.out.println(b); //prints 13```

`Integer integer = Integer.valueOf((int) Math.round(myDouble)));`

`Integer integer = myDouble == null ? null : Integer.valueOf((int) Math.round(myDouble)));`

`Math.round()在`处理空值和无穷大的效果比较好。

```Double foo = 123.456;
Integer bar = foo.intValue();```

1. 将Double对象转换为基础类型double。(=“拆箱”)
2. 将double转换为int。(=“转换”)
3. 将原始整数转换回Integer对象。(=“装箱”)

Java：

```// starting point
Double myDouble = Double.valueOf(10.0);

// step 1: unboxing
double dbl = myDouble.doubleValue();

// step 2: casting
int intgr = (int) dbl;

// step 3: boxing
Integer val = Integer.valueOf(intgr);```

```Double myDouble = Double.valueOf(10.0);
Integer val = Integer.valueOf(myDouble.intValue()); // the simple way```

```Double myDouble = null;
Integer val = Integer.valueOf(myDouble.intValue()); // will throw a NullPointerException

// a null-safe solution:
Integer val = (myDouble == null)? null : Integer.valueOf(myDouble.intValue());```

• 1/0=+无穷大
• -1/0=-无穷大
• 0/0=未定义(NaN)

```// null-safe and with better rounding
long rounded = (myDouble == null)? 0L: Math.round(myDouble.doubleValue());
Integer val = Integer.valueOf(rounded);```

```Integer val1 = 10; // works
Integer val2 = 10.0; // doesn't work

Double val3 = 10; // doesn't work
Double val4 = 10.0; // works

Double val5 = null;
double val6 = val5; // doesn't work```

```double val7 = (double) 10; // works
Double val8 = (Double) Integer.valueOf(10); // doesn't work
Integer val9 = (Integer) 9; // pure nonsense```

```long rounded = (myDouble == null)? 0L: Math.round(myDouble.doubleValue());
Integer val = new Integer(rounded); // waste of memory```

```double d = 9.5;
int i = (int)d;
//i = 9

Double D = 9.5;
int i = Integer.valueOf(D.intValue());
//i = 9

double d = 9.5;
Long L = Math.round(d);
int i = Integer.valueOf(L.intValue());
//i = 10```

```Double d = 5.25;
Integer i = d.intValue(); // i becomes 5```

```double d = 5.25;
int i = (int) d;```