In this guide, you will learn about the Double parseDouble() method in Java programming and how to use it with an example.
1. Double parseDouble() Method Overview
Definition:
The parseDouble() method of the Java Double class converts a string representation of a floating-point number to its double primitive type.
Syntax:
double Double.parseDouble(String s)
Parameters:
String s: The string to be parsed.
Key Points:
- If the string does not contain a parsable double, a NumberFormatException will be thrown.
- This method can handle string representations of both regular floating-point numbers and numbers in scientific notation.
- Leading and trailing whitespaces in the string are allowed and will be ignored during the parsing.
- The method is static, so it's invoked on the class (Double) and not on an instance of the class.
2. Double parseDouble() Method Example
public class ParseDoubleExample {
public static void main(String[] args) {
// Parse a regular floating-point number
String numberStr = "123.45";
double value = Double.parseDouble(numberStr);
System.out.println("Parsed double from string: " + value);
// Parse a number in scientific notation
String sciNotationStr = "1.23e2"; // Represents 1.23 * 10^2
double sciValue = Double.parseDouble(sciNotationStr);
System.out.println("Parsed double from scientific notation: " + sciValue);
}
}
Output:
Parsed double from string: 123.45 Parsed double from scientific notation: 123.0
Explanation:
In the provided example, we first parsed a regular floating-point number "123.45" from a string using the parseDouble() method.
We then demonstrated the method's capability to handle scientific notation by parsing the string "1.23e2", which represents the value \(1.23 \times 10^2\), resulting in a double value of 123.0.
Comments
Post a Comment
Leave Comment