In this Java program, we will learn to convert the String variables to a double value using several different methods.
Using Double.parseDouble() method
String str = "42.5"; double d = Double.parseDouble(str);
This method takes a String as an argument and returns the equivalent double representation. If the string is not a valid double representation, it will throw NumberFormatException.
Using Double.valueOf() method
String str = "42.5"; double d = Double.valueOf(str);
This method also takes a String as an argument and returns a Double object that contains the double value represented by the string. It throws NumberFormatException if the string is not a valid double representation.
Using DecimalFormat class
String str = "42.5"; DecimalFormat df = new DecimalFormat(); double d = df.parse(str).doubleValue();
This method uses the DecimalFormat class to parse the string and returns the double value represented by the string.
Java Program to Convert String to Double
public class StringToDoubleExample {
public static void main(String[] args) {
String str = "42.5";
// Using Double.parseDouble() method
try {
double d1 = Double.parseDouble(str);
System.out.println("Double.parseDouble(): " + d1);
} catch (NumberFormatException e) {
System.out.println("The string is not a valid double");
}
// Using Double.valueOf() method
try {
double d2 = Double.valueOf(str);
System.out.println("Double.valueOf(): " + d2);
} catch (NumberFormatException e) {
System.out.println("The string is not a valid double");
}
// Using DecimalFormat class
try {
DecimalFormat df = new DecimalFormat();
double d3 = df.parse(str).doubleValue();
System.out.println("DecimalFormat: " + d3);
} catch (ParseException e) {
System.out.println("The string is not a valid double");
}
}
}
Output
Double.parseDouble(): 42.5 Double.valueOf(): 42.5 DecimalFormat: 42.5
This program defines a String variable str with the value "42.5". Then, it demonstrates the use of the Double.parseDouble() method, the Double.valueOf() method, and the DecimalFormat class for converting the String to a double.