This example shows how to convert string to double in Java using the parseDouble method of the Double wrapper class including the NumberFormatException.
How to convert String to double in Java?
To convert string to double, use the parseDouble
method of the Double wrapper class.
1 |
public static double parseDouble(String stringDoubleNumber) |
This method returns double primitive value by parsing the input string value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.javacodeexamples.basic; public class StringToDoubleExample { public static void main(String[] args){ String strNumber = "10.378"; /* * Use Double.parseDouble() method to * convert String to double primitive value */ double d = Double.parseDouble(strNumber); System.out.println("String to double: " + d); } } |
Output
1 |
String to double: 10.378 |
Important Note:
If the input string value cannot be parsed to a double value, the parseDouble
method throws a NumberFormatException exception.
Also, if the string is null, the parseDouble
method throws a NullPointerException exception.
1 2 |
String strNumber = "1312a43.324"; double d = Double.parseDouble(strNumber); |
Output
1 2 3 4 |
Exception in thread "main" java.lang.NumberFormatException: For input string: "1312a43.324" at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source) at java.lang.Double.parseDouble(Unknown Source) at com.javacodeexamples.basic.StringToDoubleExample.main(StringToDoubleExample.java:8) |
Here are some of the example string values and their possible outputs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//decimal(.) sign is allowed, output 783.43 System.out.println( Double.parseDouble("783.43") ); //Plus sign is allowed as a first char, output 45234.422 System.out.println( Double.parseDouble("+45234.422") ); //Minus sign is allowed as a first char, output -45234.422 System.out.println( Double.parseDouble("-45234.422") ); //NumberFormatException System.out.println( Double.parseDouble("4532.45.432") ); //NumberFormatException System.out.println( Double.parseDouble("213a.324") ); /* * even an empty string is not allowed, * NumberFormatException is thrown for input String: "" */ System.out.println( Double.parseDouble("") ); |
Please note that the “+” (plus sign) or “-” (Minus sign) is allowed as a first character of the string to denote positive and negative value numbers respectively.
This example is a part of the Java Basic Examples and Java Type conversion Tutorial.
Please let me know your views in the comments section below.