Java 程序将 double 类型变量转换为 int

要理解此示例,您应该具备以下 Java 编程的知识:

示例 1:使用类型转换将 double 转换为 int

public class Main {
  public static void main(String[] args) {

    // create double variables
    double a = 23.78D;
    double b = 52.11D;

    // convert double into int
    // using typecasting
    int c = (int)a;
    int d = (int)b;

    System.out.println(c);    // 23
    System.out.println(d);    // 52
  }
}

在上面的例子中,我们有 double 类型变量 ab . 注意这一行,

int c = (int)a;

在这里,较高的数据类型 double 被转换为较低的数据类型 int 。因此,我们需要在括号内显式使用 int

这称为缩小类型转换。要了解更多信息,请访问Java 类型转换

注意:当 double 的值小于或等于 int 的最大值 2147483647 时,此程序有效。否则会造成数据丢失。

示例 2:使用 Math.round() 将 double 转换为 int

我们还可以使用 Math.round() 方法将 double 类型变量转换为 int。例如,

public class Main {
  public static void main(String[] args) {

    // create double variables
    double a = 99.99D;
    double b = 52.11D;

    // convert double into int
    // using typecasting
    int c = (int)Math.round(a);
    int d = (int)Math.round(b);

    System.out.println(c);    // 100
    System.out.println(d);    // 52
  }
}

在上面的例子中,我们创建了两个 double 变量 ab . 注意这一行,

int c = (int)Math.round(a);

这里,

  • Math.round(a) - 将 decimal 值转换为 long
  • (int) -使用类型转换将 long 值转换为 int

Math.round() 方法将十进制值四舍五入到最接近的 long 值。要了解更多信息,请访问 Java Math round()

示例 3:将 Double 转换为 int

我们还可以 使用 intValue() 方法将 Double 类的实例转换为 int。例如,

public class Main {
  public static void main(String[] args) {

    // create an instance of Double
    Double obj = 78.6;

    // convert obj to int
    // using intValue()
    int num = obj.intValue();

    // print the int value
    System.out.println(num);    // 78
  }
}

在这里,我们使用了 Double 对象的 intValue() 方法将其转换为 int

Double 是 Java 的包装类。要了解更多信息,请访问Java 包装器类