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

它会抛出一个异常

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


当前回答

Double不是Integer,所以强制转换无效。注意Double类和Double原语之间的区别。还要注意,Double是一个数字,因此它有方法intValue,您可以使用该方法获取作为原始int的值。

其他回答

是这样的:

Double foo = 123.456;
Integer bar = foo.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。

使用doubleNumber.intValue();方法。

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

例子

int intResult = newDoubleObj.intValue();

Double不是Integer,所以强制转换无效。注意Double类和Double原语之间的区别。还要注意,Double是一个数字,因此它有方法intValue,您可以使用该方法获取作为原始int的值。