double类型转换成int类型

本文通过一个Java案例演示了double类型转换为int类型的细节过程,包括具体的代码实现、运行结果展示及背后的源码解析,并提供了进一步尝试转换为其他类型的启示。

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、授之以渔 

这个是官方源码的构造方法,我们可以看到还可以尝试转换为其他类型,比如转换为short类型。 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞流2023

小主,破费了,回头请你喝咖啡!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值