Double is not converting to an int

17,859

Solution 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); 

Solution 2

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

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

Solution 3

This

Double d = 10.9;

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

double d = 10.9;
Share:
17,859
Mayank Pratap
Author by

Mayank Pratap

Updated on August 05, 2022

Comments

  • Mayank Pratap
    Mayank Pratap over 1 year

    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);
    
  • Sri Harsha Chilakapati
    Sri Harsha Chilakapati over 11 years
    Typo convertig. n is missing.
  • BaSsGaz
    BaSsGaz over 6 years
    You can not cast wrapper like Double to primitive type like int directly.Not always (double) new Integer(5); would work.