The parseDouble method is the most used to do this type of conversion.
public class ConvertStringToDouble {
public static void main(String[] args) {
String aString = "700";
double aDouble = Double.parseDouble(aString);
System.out.println(aDouble);
}
}
You can also make CAST
to convert to your type.
double aDouble = (Double)aString;
Using Double.valueOf
The Static method Double.valueOf () will return a Double object while maintaining the value of the specified string.
Syntax
String numberAsString = "153.25";
double number = Double.valueOf(numberAsString);
System.out.println("The number is: " + number);
Convert using new Double (String) .doubleValue ()
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;
double number = new Double("153.25").doubleValue();
Converts using DecimalFormat
The java.text.DecimalFormat class is a class that can be used to convert a number to its String representation. It can also be used in reverse - it can parse a String in its numeric 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.");
}
Note: If your string contains , in place of . , make a replace before attempting to convert.
>
String number = "123,321";
double value = Double.parseDouble(number.replace(",",".") );
See worked here.