How does double to int cast work in Java

前端 未结 3 1925
一整个雨季
一整个雨季 2020-11-27 19:26

I am new to Java, and wondering how does double to int cast work ? I understand that it\'s simple for long to int by taking the low 32 bits, but what about double (64 bits)

3条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 19:54

    Java truncates its value if you use (int) cast, as you may notice:

        double d = 2.4d;
        int i = (int) d;
        System.out.println(i);
        d = 2.6;
        i = (int) d;
        System.out.println(i);
    

    Output:

    2
    2
    

    Unless you use Math.round, Math.ceil, Math.floor...

提交回复
热议问题