Double不转换为int

Double不转换为int

问题描述:

这段代码已经写入,将 double 转换为 int 获取异常。

This code I have written to convert double into int getting an exception.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Cannot cast from Double to int

这是我的代码

Double d = 10.9;    
int i = (int)(d);


Double 是原始 double 之上的包装器类。它可以转换为 double ,但不能直接转换为 int

Double is a wrapper class on top of the primitive double. It can be cast to double, but it cannot be cast to int directly.

如果您使用 double 而不是 Double ,则会编译:

If you use double instead of Double, it will compile:

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

您还可以添加一个演员到 double 在中间,像这样:

You can also add a cast to double in the middle, like this:

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