本文翻译自:Cast Double to Integer in Java
Any way to cast java.lang.Double
to java.lang.Integer
? 有什么方法可以将java.lang.Double
为java.lang.Integer
吗?
It throws an exception 它引发了一个例外
"java.lang.ClassCastException: java.lang.Double incompatible with java.lang.Integer" “java.lang.ClassCastException:java.lang.Double与java.lang.Integer不兼容”
#1楼
参考:https://stackoom.com/question/cBva/在Java中将Double转换为Integer
#2楼
double a = 13.34;
int b = (int) a;
System.out.println(b); //prints 13
#3楼
I see three possibilities. 我看到三种可能性。 The first two cut off the digits, the last one rounds to the nearest Integer. 前两个截断数字,最后一个截止到最接近的整数。
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
#4楼
Double d = 100.00;
Integer i = d.intValue();
One should also add that it works with autoboxing. 还应该补充一点,它适用于自动装箱。
Otherwise, you get an int (primitive) and then can get an Integer from there: 否则,你得到一个int(原始),然后从那里得到一个Integer:
Integer i = new Integer(d.intValue());
#5楼
Indeed, the simplest way is to use intValue()
. 实际上,最简单的方法是使用intValue()
。 However, this merely returns t