杰瑞科技汇

Java Double.parseDouble() 如何转换字符串?

Of course! In Java, Double.parseDouble() is a crucial static method used to convert a String that represents a floating-point number into a primitive double data type.

Java Double.parseDouble() 如何转换字符串?-图1
(图片来源网络,侵删)

Let's break it down in detail.

What is Double.parseDouble()?

It's a public, static method belonging to the java.lang.Double class. Its purpose is to parse the given String argument and return a double primitive value.

Method Signature:

public static double parseDouble(String s) throws NumberFormatException

Key Characteristics

  1. Static Method: You don't need to create an instance of the Double class to call it. You call it directly on the class: Double.parseDouble(...).
  2. Returns a Primitive double: This is a key difference from the Double constructor, which returns a Double object (a wrapper class).
  3. Throws NumberFormatException: If the String does not contain a parsable number, this method will throw a NumberFormatException. This is a checked exception, meaning you should handle it (e.g., with a try-catch block) or declare it in your method's signature.

Basic Usage Example

Here is the simplest and most common way to use the method.

Java Double.parseDouble() 如何转换字符串?-图2
(图片来源网络,侵删)
public class ParseDoubleExample {
    public static void main(String[] args) {
        String strNumber = "123.456";
        double number;
        try {
            // Convert the String to a primitive double
            number = Double.parseDouble(strNumber);
            System.out.println("String: " + strNumber);
            System.out.println("Primitive double: " + number);
            System.out.println("Type of 'number': " + ((Object)number).getClass().getSimpleName()); // Shows it's a primitive
        } catch (NumberFormatException e) {
            System.out.println("Invalid number format: " + strNumber);
        }
    }
}

Output:

String: 123.456
Primitive double: 123.456
Type of 'number': double

Handling Exceptions

Since the method can throw a NumberFormatException, it's best practice to wrap the call in a try-catch block when the input string's format is uncertain.

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        String[] inputs = {"3.14", "-99.0", "hello", "123abc", "1,000.50"};
        for (String input : inputs) {
            try {
                double d = Double.parseDouble(input);
                System.out.println("Successfully parsed '" + input + "' to: " + d);
            } catch (NumberFormatException e) {
                // This block will execute for invalid formats
                System.out.println("Could not parse '" + input + "'. It's not a valid double.");
            }
        }
    }
}

Output:

Successfully parsed '3.14' to: 3.14
Successfully parsed '-99.0' to: -99.0
Could not parse 'hello'. It's not a valid double.
Could not parse '123abc'. It's not a valid double.
Could not parse '1,000.50'. It's not a valid double.

Note: The comma in "1,000.50" makes it an invalid format for parseDouble.

Java Double.parseDouble() 如何转换字符串?-图3
(图片来源网络,侵删)

Edge Cases and Special Values

Double.parseDouble() is quite robust and can handle several special string values defined by the IEEE 754 standard.

String Input Parsed double Value Description
"Infinity" Double.POSITIVE_INFINITY Positive infinity.
"Infinity" (case-insensitive) Double.POSITIVE_INFINITY Also works with "INFINITY".
"-Infinity" Double.NEGATIVE_INFINITY Negative infinity.
"NaN" Double.NaN "Not a Number". Used for undefined or unrepresentable values.
"123.45" 45 Standard positive number.
"-123.45" -123.45 Standard negative number.
" 123.45 " 45 Ignores leading and trailing whitespace.
"1.23e10" 0 Scientific notation.
"1.23E-5" 0000123 Scientific notation with a negative exponent.

Example of Special Values:

public class SpecialValuesExample {
    public static void main(String[] args) {
        System.out.println(Double.parseDouble("Infinity"));       // Infinity
        System.out.println(Double.parseDouble("-Infinity"));      // -Infinity
        System.out.println(Double.parseDouble("NaN"));            // NaN
        System.out.println(Double.parseDouble("1.23e2"));         // 123.0
        System.out.println(Double.parseDouble("  -99.99  "));     // -99.99
        // Comparing NaN
        double nanValue = Double.parseDouble("NaN");
        System.out.println("Is NaN equal to itself? " + (nanValue == nanValue)); // false
        System.out.println("Use Double.isNaN(): " + Double.isNaN(nanValue));   // true
    }
}

Double.parseDouble() vs. Double.valueOf()

This is a very common point of confusion. Here’s the difference:

Feature Double.parseDouble(String s) Double.valueOf(String s)
Return Type Primitive double Double object (a wrapper)
Purpose When you need the primitive value for calculations (e.g., with int, float). When you need an Object, for example, to store it in a collection like List<Double> or Set<Double>.
Performance Slightly more direct, no object creation. Creates a new Double object, which has a small performance overhead.

Example of the Difference:

public class ParseDoubleVsValueOf {
    public static void main(String[] args) {
        String str = "98.6";
        // Using parseDouble() -> gets a primitive
        double primitiveDouble = Double.parseDouble(str);
        System.out.println("Primitive double: " + primitiveDouble);
        System.out.println("Is it a primitive? " + (primitiveDouble instanceof Double)); // false
        // Using valueOf() -> gets an object
        Double doubleObject = Double.valueOf(str);
        System.out.println("\nDouble object: " + doubleObject);
        System.out.println("Is it an object? " + (doubleObject instanceof Double)); // true
        // Autoboxing: You can assign a primitive to a reference variable of the wrapper type
        Double anotherObject = primitiveDouble; // Java automatically "boxes" the primitive
        System.out.println("\nAutoboxed object: " + anotherObject);
    }
}

Summary: When to Use Which?

  • Use Double.parseDouble() when:

    • You are reading numbers from a file, user input, or an API.
    • You need to perform mathematical operations.
    • You want to avoid the overhead of creating an object.
    • You are working with legacy code or APIs that require primitive types.
  • Use Double.valueOf() when:

    • You need to store the number in a collection that requires objects (e.g., ArrayList<Double>).
    • You need to pass the number to a method that expects an object.
    • You want to leverage methods from the Double class, like doubleValue(), intValue(), isNaN(), etc., directly on the variable.
分享:
扫描分享到社交APP
上一篇
下一篇