Java String to double

In Java, you can convert a String to a double using the Double.parseDouble() method. Here’s how you can do it:

1. Double.parseDouble()

The Double.parseDouble() method is the most commonly used method to convert a String to a double. If the string is not a valid representation of a double, it throws a NumberFormatException.

Example:


public class StringToDoubleExample {
    public static void main(String[] args) {
        String str = "156.67";
        
        // Convert String to double using parseDouble()
        double num = Double.parseDouble(str);
        
        System.out.println("Converted double: " + num);
    }
}

Output: Converted double: 156.67

Explanation:

1. Double.parseDouble(str) converts the string str to a double.

2. If the string cannot be parsed into a valid double (e.g., “abc”), it throws a NumberFormatException.

How to handle Exceptions?

If the string is not a valid number, Double.parseDouble() will throw a NumberFormatException. You should handle this exception to prevent program crashes.

Example


public class StringToDoubleExample {
    public static void main(String[] args) {
        String str = "abcd";  // Invalid number string
        
        try {
            double num = Double.parseDouble(str);  // This will throw NumberFormatException
            System.out.println("Converted double: " + num);
        } catch (NumberFormatException e) {
            System.out.println("Error: Invalid number format");
        }
    }
}

Output: Error: Invalid number format