Java 类型转换方法

Java double转int有3种方法,它们分别是:

  1. 使用类型转换将double转换为int
  2. 使用Math.round()将double转换为int,该方法可以让double值四舍五入到最接近的int值。
  3. 使用double.intValue()将double转换为int。

下面分别介绍这3种方式转换的例子。

1. 使用类型转换

使用类型转换的方式比较简单,就是在double类型的值前面用int关键字,但是它没有对double值进行四舍五入,而是直接截断了小数点后面的数字,如果结果想要更准确的精度,建议使用第二种方法Math.round()进行转换。

public class Double2IntExample {
    public static void main(String args[]){
        double dnum = 12.99;

        int inum=(int)dnum;

        System.out.println(inum);
    }
} 
输出:
12

我们看到结果输出的是12,截断了小数0.99,接下来看第二种方式。

2.使用Math.round()方法

Math.round()方法是java的数学方法,也是面试题之一。看下面的例子。

public class Double2IntExample2 {
    public static void main(String args[]){
        double dnum = 12.99;

        int inum=(int) Math.round(dnum);

        System.out.println(inum);
    }
} 
输出:
13 

3. 使用Double.intValue()方法

这里介绍java的Double包装类方法,它和第一种方法相同,会截断小数位。

public class Double2IntExample3 {
    public static void main(String args[]){
        Double dnum = 12.99;
        int inum = dnum.intValue();
        System.out.println(inum);
    }
}
输出:
12