Java 程序将字符串变量转换为 double
要理解此示例,您应该具备以下 Java 编程的知识:
示例 1:使用 parseDouble() 将字符串转换为双精度
public class Main {
public static void main(String[] args) {
// create string variables
String str1 = "23";
String str2 = "456.6";
// convert string to double
// using parseDouble()
double num1 = Double.parseDouble(str1);
double num2 = Double.parseDouble(str2);
// print double values
System.out.println(num1); // 23.0
System.out.println(num2); // 456.6
}
}
在上面的示例中,我们使用了 Double
类的 parseDouble()
方法将字符串变量转换为 double
。
这里,Double
是 Java 中的一个包装类。要了解更多信息,请访问Java 包装器类。
注意:字符串变量应该代表数字值。否则编译器会抛出异常。例如,
public class Main {
public static void main(String[] args) {
// create a string variable
String str1 = "abcd";
// convert string to double
// using parseDouble()
double num1 = Double.parseDouble(str1);
// print double values
System.out.println(num1); // 抛出异常 NumberFormatException
}
}
示例 2:使用 valueOf() 将字符串转换为双精度
我们还可以使用 valueOf()
方法将字符串变量转换为双精度值。例如,
public class Main {
public static void main(String[] args) {
// create string variables
String str1 = "6143";
String str2 = "21312";
// convert String to double
// using valueOf()
double num1 = Double.valueOf(str1);
double num2 = Double.valueOf(str2);
// print double values
System.out.println(num1); // 6143.0
System.out.println(num2); // 21312.0
}
}
在上面的例子中, Double
类的 valueOf()
方法将字符串值转换为 double
.
在这里,该 valueOf()
方法实际上返回了 Double
类的一个对象。但是,对象会自动转换为原始类型。这在 Java 中称为拆箱。要了解更多信息,请访问Java 自动装箱和拆箱。
也就是,
// valueOf() returns object of Double
// object is converted into double
double num1 = Double obj = Double.valueOf(str1);
示例 3:将包含逗号的字符串转换为双精度
public class Main {
public static void main(String[] args) {
// create string variables
String str = "614,33";
// replace the , with .
str = str.replace(",", ".");
// convert String to double
// using valueOf()
double value = Double.parseDouble(str);
// print double value
System.out.println(value); // 61433
}
}
在上面的例子中,我们创建了一个名为 str
的字符串。注意这一行,
str = str.replace(",", "");
此处,该 replace()
方法将字符串中的逗号替换为空。要了解有关替换字符的更多信息,请访问Java String replace()。
然后我们使用该 Double.parseDouble()
方法将字符串转换为 double
.