Java教程

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

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

在这个程序中,我们将学习在 Java 中将 double 变量转换为整数(int)。
要理解此示例,您应该了解以下Java 编程主题:
Java 数据类型(原生)

示例 1: 使用类型转换将 double 转换为 int 的 Java 程序

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。例如,
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
  }
}
在上面的例子中,我们创建了两个名为 abdouble 变量。注意这一行,
int c = (int)Math.round(a);
这里,
Math.round(a)-将 decimal 值转换为 long (int)-使用类型转换将 long 值转换为 int
Math.round() 方法将十进制值四舍五入到最接近的 long 值。要了解更多信息,请访问 Java Math round()。

示例 3: 将 Double 转换为 int 的 Java 程序

我们还可以使用 intValue() 方法将 Double 类的实例转换为 int。例如,
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
  }
}
这里,我们使用了 intValue()方法将 Double的对象转换为 int
Double 是 Java 中的包装类。要了解更多信息,请访问 Java Wrapper Class。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4