有办法将java.lang.Double转换为java.lang.Integer吗?
它会抛出一个异常
" . lang。ClassCastException: java.lang.Double不兼容java.lang.Integer"
有办法将java.lang.Double转换为java.lang.Integer吗?
它会抛出一个异常
" . lang。ClassCastException: java.lang.Double不兼容java.lang.Integer"
当前回答
你需要使用方法intValue()像这样显式地获取int值:
Double d = 5.25;
Integer i = d.intValue(); // i becomes 5
Or
double d = 5.25;
int i = (int) d;
其他回答
Double不是Integer,所以强制转换无效。注意Double类和Double原语之间的区别。还要注意,Double是一个数字,因此它有方法intValue,您可以使用该方法获取作为原始int的值。
首先你应该用双份而不是双份。
例子
int intResult = newDoubleObj.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 = 100.00;
Integer i = d.intValue();
还应该补充一点,它与自动装箱一起工作。
否则,你得到一个int(原语),然后可以从那里得到一个Integer:
Integer i = new Integer(d.intValue());