A Java String can be converted to a double easily using built-in Wrapper Classes. Let’s take a look at how to convert
a String to an double in Java. The example below will use functionality from the Java Number classes.
We declare and initialize a String below that could represent a double value.
String theString = "123.5";
If we need to convert this string to double we should use one of the built-in Java Numbers Classes. You can check out the Java Number Classes and further details using the official Java Tutorials here. The Number Classes are helper classes that allow you to “wrap” the primitive Java number data types (int, double, float, etc.) and manipulate them using helper methods. There is a wrapper class for each of the primitive data types. The example we’re going to look at the uses the Double wrapper class which can be used with the primitive Java double data type. We are going to use the built in Java Double Wrapper Class to do the conversion of our string to a double.
double myNumber = Double.parseDouble(theString);
We declared and created a new double named myNumber in the code snippet above. We parsed our String created earlier and created a new double that using the built-in Java Wrapper Double Class. The value of myNumber is 123.5 after using the Wrapper Class. Whenever you are converting a String to double, this is the recommended approach.
We are missing a catch statement for a possible exception. You can either surround the parseDouble method with a try catch block, or declare a throws statement on the calling method. The parseDouble method can throw the NumberFormatException. The code below implements a try catch block to handle the exception.
double myNumber;
try {
myNumber = Double.parseDouble(theString);
} catch (NumberFormatException e) {
System.out.println("Failed to convert String to double");
}
NumberFormatException will be thrown if your String cannot be converted to a double. As an example, a String that contains text like "12a" would throw NumberFormatException for obvious reasons.