
* Java Program - Convert String to Double In this example, we shall use Double.parseDouble() method and pass a string that can be parsed to a valid double value. Run the above program and the String is converted to Double.

If you do not provide a valid string that is parsable double, Double.parseDouble() throws NumberFormatException. A number that is out of range for a double value.If the string contains invalid characters that does not parse to a double value.Some of the scenarios that could throw this error are: In the following example program, we shall take a string which does not contain a valid double value.

Run the above program and parseDouble() throws NumberFormatException.Īny value that is outside the range will make parseDouble() to throw this error. Exception in thread "main" : For input string: "5-354"Īt java.base/.readJavaFormatString(Unknown Source)Īt java.base/.parseDouble(Unknown Source)Īt java.base/(Unknown Source)Īt StringToDouble.main(StringToDouble.java:12)Īlso, if null is passed to Double.parseDouble(), the function throws NullPointerException. Run the above program and parseDouble() throws NullPointerException. } String to Double using Double.valueOf()Įxception in thread "main" Īs Double.parseDouble() can throw NullPointerException or NumberFormatException, it is a good practice to surround the function parseDouble() with Java Try Catch and handle the exceptions accordingly. You can also use Double.valueOf() function to convert a string to double. In the following example, we shall use the method valueOf() to get double value from string.
