[英]Double is not converting to an int
This code I have written to convert double
into int
getting an exception.我编写的这段代码将double
转换为int
出现异常。
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot cast from Double to int
This is my code这是我的代码
Double d = 10.9;
int i = (int)(d);
Double
is a wrapper class on top of the primitive double
. Double
是原始double
之上的包装类。 It can be cast to double
, but it cannot be cast to int
directly. 它可以强制转换为double
,但不能直接转换为int
。
If you use double
instead of Double
, it will compile: 如果你使用double
而不是Double
,它将编译:
double d = 10.9;
int i = (int)(d);
You can also add a cast to double
in the middle, like this: 您还可以在中间添加一个转换为double
,如下所示:
int i = (int)((double)d);
thats because you cant mix unboxing (converting your Double
to a double primitive
) and casting. 多数民众赞成因为你不能混合拆箱(将你的Double
转换为双primitive
)和铸造。 try 尝试
int i = (int)(d.doubleValue());
This 这个
Double d = 10.9;
is your error. 是你的错误。 You are using wrapper classes instead of data types. 您正在使用包装类而不是数据类型。 Use 使用
double d = 10.9;
You can not cast wrapper like Double to primitive type like int directly. 您不能直接将像Double这样的包装器转换为原始类型。
You can try this - 你可以尝试这个 -
int i = (int)((double)d);
For more check following link - http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html 有关更多检查以下链接 - http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.