如何将 Java double
转换为int
原文:https://www.studytonight.com/java-type-conversion/how-to-convert-java-double-to-int
在 Java 中,可以使用类型转换操作符将double
转换为int
。这是因为,为了将较高的数据类型转换为较低的数据类型,需要执行类型转换,这种类型的转换称为类型转换。
在 Java 中,类型转换是通过类型转换运算符(数据类型)来执行的。
例 1:
这里,使用 typecasting 运算符将基元双精度值转换为 int。
public class StudyTonight
{
public static void main(String args[])
{
double d = 500.0;
int i = (int)d; //typecasting
System.out.println("The int value is " +i);
}
}
整数值为 500
另外,我们可以通过 Double 类的 intValue() 方法将一个 double 对象转换成一个 int。
例 2:
这里Double
对象通过 intValue() 方法转换为 int。
public class StudyTonight
{
public static void main(String args[])
{
Double d = new Double(50.78);
int i = d.intValue();
System.out.println("The int value is : " +i);
}
}
int 值为:50
例 3:
这里,基元双精度值被转换成 int 类型的值。
public class StudyTonight
{
public static void main(String args[])
{
Double myDouble = Double.valueOf(10.0);
int val = Integer.valueOf(myDouble.intValue());
System.out.println("The int value is : " +val);
}
}
int 值为:10