In Java, a String containing a valid numeric value can be converted into a double or Double using the methods provided by the Double class. The commonly used approaches are parseDouble() and valueOf(). The parseDouble() method returns a primitive double, whereas valueOf() returns a Double object.
- Double.valueOf() converts a String into a Double object.
- Both methods accept strings containing valid floating-point values.
Methods for String-to-Double Conversion
1. Using parseDouble() Method
The Double.parseDouble() method converts a string representing a valid floating-point number into a primitive double.
Syntax
double d = Double.parseDouble(str);
Example: Program to Convert String to Double Using parseDouble() Method.
class Geeks {
public static void main(String[] args) {
String str = "2033.12244";
double value = Double.parseDouble(str);
System.out.println(value);
}
}
Output
2033.12244
Explanation: The string "2033.12244" is passed to Double.parseDouble(), which converts it into the primitive double value 2033.12244.
2. Using valueOf() Method of Double Class
The Double.valueOf() method converts a string into a Double object representing the specified numeric value.
Syntax
double d = Double.valueOf(str);
Example: Program to Convert String to Double Using valueOf() Method.
public class Geeks
{
// Main driver method
public static void main(String args[])
{
// Creating and initializing a string
String str = "2033.12244";
// Converting the above string to Double type
double d = Double.valueOf(str);
// Printing above string as double type
System.out.println(d);
}
}
Output
2033.12244
Explanation: The Double.valueOf() method parses the string and returns a Double object containing the corresponding numeric value.