JavaDevNotes.com

Java String To Double Examples

This post will show examples on how to convert Java String To Double. It is a commonly encountered case to convert a String value to double when programming with the Java language.
Here are some examples for performing the conversion:

Convert using Double.parseDouble()

The Double.parseDouble() static method parses the string argument and returns a double value.

Syntax
public 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.

Example
String 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.25
This 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.


Convert using Double.valueOf()

The Double.valueOf() static method will return a Double object holding the value of the specified String.

Syntax
public 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.25
This 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.


Convert using new Double(String).doubleValue()

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();


Convert using DecimalFormat

The class java.text.DecimalFormat is a class that can be used to convert a number to it's String representation. It can also be used the other way around - it can parse a String into it's numerical representation.
Example
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.25
Note that the parse() method will throw a ParseException when there are problems encountered with the String.

String Tutorials And Examples