The parseDouble method is the most used to make 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 do the CAST
to convert to your type.
double aDouble = (Double)aString;
Using Double.valueOf
The static method Double.valueOf() will return a Double object holding the value of the specified sequence .
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 it 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 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.");
}
Obs: if your string contained , in place of . , the ideal and make a replace before trying converts.
String number = "123,321";
double value = Double.parseDouble(number.replace(",",".") );
See worked here.
How is it null? Here it occurred normal, see: https://ideone.com/BZ0T0z
– user28595
You want to turn an 'x' value into String, for example '1.2', to double or want to actually turn 'x' to double?
– Rafael
Let’s say the value of X is: String x = 700; How do I pass this value (700) to a Double variable?
– Alexandre Vieira de Souza
What has in its value variable before you to it for the Double.parseDouble?
– Marco Souza
http://stackoverflow.com/questions/5769669/convert-string-to-double-in-java
– Marco Souza
http://stackoverflow.com/questions/13166386/parsing-string-to-double-java
– Marco Souza
Alexandre, see the example of the link I sent, no problem. This method works normally.
– user28595