示例 1:Java 使用类型转换将 double 转换为 int
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 类型的变量 a 和 b。注意这一行,
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
}
}
在上面的示例中,我们创建了两个名为 a 和 b 的 double 变量。注意这一行,
int c = (int)Math.round(a);
这里,
- Math.round(a) - 将
decimal值转换为long值 - (int) - 使用类型转换将
long值转换为int
Math.round() 方法将 decimal 值四舍五入到最接近的 long 值。要了解更多,请访问 Java Math round()。
示例 3:Java 将 Double 转换为 int 的程序
我们也可以使用 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包装类。