如何在Java中将字符串转换为双精度
时间:2020-01-09 10:35:29 来源:igfitidea点击:
要将Java中的String转换为double,可以使用以下选项之一
- Double.parseDouble(String s)-返回一个新的double,它初始化为指定String表示的值。如果字符串不包含可分析的double则抛出NumberFormatException。
- Double.valueOf(String s)–返回一个Double对象,其中包含参数字符串s表示的double值。如果字符串不包含可解析的数字,则引发NumberFormatException。
如我们所见,parseDouble()方法返回一个double原语,而valueOf()方法则返回一个Double对象。
Java示例,使用Double.parseDouble将String转换为double
public class StringToDouble { public static void main(String[] args) { String num = "145.34526"; try{ double d = Double.parseDouble(num); System.out.println("Value- " + d); // can be used in arithmetic operations now System.out.println(d+"/3 = " + d/3); }catch(NumberFormatException ex){ System.out.println("Error while conversion " + ex.getMessage()); } } }
输出:
Value- 145.34526 145.34526/3 = 48.44842
对于双精度数字,可以使用" d"或者" D"(偶数f或者F表示双精度),因此这样的字符串–" 145.34d"在转换时不会导致NumberFormatException。但是使用" 145.34c"之类的其他字母会抛出异常。
public class StringToDouble { public static void main(String[] args) { String num = "145.34526d"; try{ double d = Double.parseDouble(num); System.out.println("Value- " + d); // can be used in arithmetic operations now System.out.println(d+"/3 = " + d/3); }catch(NumberFormatException ex){ System.out.println("Error while conversion " + ex.getMessage()); } } }
输出:
Value- 145.34526 145.34526/3 = 48.44842
Java示例,使用Double.valueOf将String转换为double
public class StringToDouble { public static void main(String[] args) { String str = "-245.67456"; try{ Double d = Double.valueOf(str); System.out.println("value- " + d); }catch(NumberFormatException exp){ System.out.println("Error in conversion " + exp.getMessage()); throw exp; } } }
输出:
value- -245.67456
NumberFormatException
在Java中将字符串转换为双精度时,如果传递了无效的数字字符串进行转换,则会引发NumberFormatException。
public class StringToDouble { public static void main(String[] args) { String str = "45.674c"; try{ Double d = Double.valueOf(str); System.out.println("value- " + d); }catch(NumberFormatException exp){ System.out.println("Error in conversion " + exp.getMessage()); throw exp; } } }
输出:
Error in conversion For input string: "45.674c"Exception in thread "main" java.lang.NumberFormatException: For input string: "45.674c" at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054) at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at java.base/java.lang.Double.parseDouble(Double.java:543) at java.base/java.lang.Double.valueOf(Double.java:506) at com.theitroad.programs.StringToDouble.main(StringToDouble.java:8)