Double is not converting to an int

大兔子大兔子 提交于 2019-12-18 04:53:11

问题


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

This is my code

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

回答1:


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.

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

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

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

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



回答2:


thats because you cant mix unboxing (converting your Double to a double primitive) and casting. try

int i = (int)(d.doubleValue());



回答3:


This

Double d = 10.9;

is your error. You are using wrapper classes instead of data types. Use

double d = 10.9;



回答4:


You can not cast wrapper like Double to primitive type like int directly.

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



来源:https://stackoverflow.com/questions/14088522/double-is-not-converting-to-an-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!