Cast object (type double) to int

前端 未结 3 1327
北海茫月
北海茫月 2020-12-11 08:31

Okay, so if I have this code

double a=1.5;
int b=(int)a;
System.out.println(b);

Everything works fine, but

Object a=1.5;
in         


        
3条回答
  •  囚心锁ツ
    2020-12-11 09:12

    I am not sure why your code works at all. You should not be able to cast Object to 'double' because they are incompatible types. Also casting type int to double are incompatible types. Your first block of code:

    double a=1.5;
    int b=(int)a;
    System.out.println(b);
    

    will print "1". You will lose the decimals. If you want to just print the number before the decimal point then you can format your double when you print and you won't need to cast to type int.

    But the reason the other don't work is because you are trying to cast to an incompatible type. It is strange that you say the last two blocks of code

    Object a=1.5;
    double b=(double)a;
    int c=(int)b;
    System.out.println(c);
    
    
    Object a=1.5;
    int b=(int)(double)a;
    System.out.println(b);
    

    These should not work because of incompatible types.

提交回复
热议问题