有办法将java.lang.Double转换为java.lang.Integer吗?

它会抛出一个异常

" . lang。ClassCastException: java.lang.Double不兼容java.lang.Integer"


当前回答

首先你应该用双份而不是双份。

例子

int intResult = newDoubleObj.intValue();

其他回答

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

还应该补充一点,它与自动装箱一起工作。

否则,你得到一个int(原语),然后可以从那里得到一个Integer:

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

实际上,最简单的方法是使用intValue()。然而,这仅仅返回整数部分;它不做任何舍入。如果你想要最接近Double值的Integer,你需要这样做:

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

不要忘记空大小写:

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

Math.round()相对优雅地处理奇数鸭子情况,如无穷大和NaN。

你需要使用方法intValue()像这样显式地获取int值:

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

Or

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

简单地这样做…

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

首先你应该用双份而不是双份。

例子

int intResult = newDoubleObj.intValue();