In the following example, we shall use the method valueOf() to get double value from string. You can also use Double.valueOf() function to convert a string to double. } String to Double using Double.valueOf()
Exception 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. Run the above program and parseDouble() throws NullPointerException. 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 NumberFormatException.
Any value that is outside the range will make parseDouble() to throw this error. 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. If you do not provide a valid string that is parsable double, Double.parseDouble() throws NumberFormatException. Run the above program and the String is converted to Double.
* 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. String to Double using Double.parseDouble()ĭouble.parseDouble(str) parses any parsable double value from string to double value.