The Double.parseDouble() static method parses the string argument and returns a double value.
Syntaxpublic static double parseDouble(String s) throws NumberFormatException
The parameter s will be converted to a primitive double value. Note that the method will throw a NumberFormatException if the parameter is not a valid double.
ExampleString numberAsString = "153.25"; double number = Double.parseDouble(numberAsString); System.out.println("The number is: " + number);When you run the code above, the output will show this:
The number is: 153.25This is the most common and popular solution when you need to convert a String to double. Note that the resulting value is not an instance of the Double class but just a plain primitive double value.
The Double.valueOf() static method will return a Double object holding the value of the specified String.
Syntaxpublic static Double valueOf(String s) throws NumberFormatException
Note that the method will throw a NumberFormatException if the parameter is not a valid double.
String numberAsString = "153.25"; double number = Double.valueOf(numberAsString); System.out.println("The number is: " + number);This will output:
The number is: 153.25This is the most common method when you wish to convert a String to Double. Note that the resulting value is an instance of the Double class and not a primitive double value.
Another alternative method is to create an instance of Double class and then invoke it's doubleValue() method.
Example
String numberAsString = "153.25"; Double doubleObject = new Double(numberAsString); double number = doubleObject.doubleValue();
We can shorten to:
String numberAsString = "153.25"; double number = new Double(numberAsString).doubleValue();or just:
double number = new Double("153.25").doubleValue();
String numberAsString = "153.25"; DecimalFormat decimalFormat = new DecimalFormat("#"); try { double number = decimalFormat.parse(numberAsString).doubleValue(); System.out.println("The number is: " + number); } catch (ParseException e) { System.out.println(numberAsString + " is not a valid number."); }Will output
The number is: 153.25Note that the parse() method will throw a ParseException when there are problems encountered with the String.