天天看點

double類型轉換成int類型1、案例示範 2、源碼檢視3、授之以漁 

double類型轉換成int類型1、案例示範 2、源碼檢視3、授之以漁 

1、案例示範 

public class test09 {
    public static void main(String[] args) {
        double a = 5000.44;
        double b = 100.12;

        double v = a / b;
        int i = new Double(v).intValue();
        System.out.println(i);
        System.out.println(v);
    }
}
           

運作結果:

49

49.944466640031955

2、源碼檢視

/**
     * Returns the value of this {@code Double} as an {@code int}
     * after a narrowing primitive conversion.
     * @jls 5.1.3 Narrowing Primitive Conversions
     *
     * @return  the {@code double} value represented by this object
     *          converted to type {@code int}
     */
    public int intValue() {
        return (int)value;
    }
           

通過以上的官方源碼可以發現,這個方法需要建立Double對象,才能調用這個方法。

3、授之以漁 

double類型轉換成int類型1、案例示範 2、源碼檢視3、授之以漁 

這個是官方源碼的構造方法,我們可以看到還可以嘗試轉換為其他類型,比如轉換為short類型。 

double類型轉換成int類型1、案例示範 2、源碼檢視3、授之以漁