Convert String to double in Java
To convert a Java String to a primitive double, use Double.parseDouble(). If you need a Double wrapper object instead, use Double.valueOf(). The older new Double(String) constructor is deprecated and should not be used in new code.
The conversion is parsing, not type casting. The string must contain a value that Java recognizes as a floating-point number.
Choosing between Double.parseDouble() and Double.valueOf()
| Method | Returns | Use when |
|---|---|---|
Double.parseDouble(str) | double | You need a primitive double value |
Double.valueOf(str) | Double | You specifically need the wrapper object |
new Double(str) | Double | Legacy code only; the constructor is deprecated |
1. Convert string to double using Double.parseDouble()
Double.parseDouble(str) parses the numeric text in str and returns a primitive double.
double value = Double.parseDouble(str);
In this example, the string contains a valid decimal value and is converted to double.
Java program using Double.parseDouble()
/**
* Java Program - Convert String to Double
*/
public class StringToDouble {
public static void main(String[] args) {
//a string
String str = "7.89654263548";
//convert string to double
double d = Double.parseDouble(str);
System.out.print(d);
}
}
Run the above program and the String is converted to Double.
7.896542635488555
For the exact input shown in the program, 7.89654263548, current Java prints 7.89654263548. The existing output block above contains an older value that does not match the program input.
String formats accepted by Double.parseDouble()
Double.parseDouble() accepts ordinary decimal numbers, signed values, scientific notation, and leading or trailing whitespace. Java also recognizes the special floating-point strings NaN and Infinity.
System.out.println(Double.parseDouble(" -12.5 "));
System.out.println(Double.parseDouble("1.25e3"));
System.out.println(Double.parseDouble("Infinity"));
-12.5
1250.0
Infinity
NumberFormatException for an invalid double string
If the string does not contain a parsable double, Double.parseDouble() throws NumberFormatException.
Common invalid inputs include:
- An empty or blank string.
- Text with misplaced signs or other invalid characters, such as
"5-354". - Values containing formatting that
Double.parseDouble()does not interpret, such as"1,234.5"or a locale-specific decimal comma such as"12,5".
A very large or very small numeric string is different from malformed text. If its magnitude is outside the finite double range, parsing can round it to infinity or to zero rather than throwing NumberFormatException.
Invalid string example with Double.parseDouble()
/**
* Java Program - Convert String to Double
*/
public class StringToDouble {
public static void main(String[] args) {
//a string
String str = "5-354";
//convert string to double
double n = Double.parseDouble(str);
System.out.print(n);
}
}
Run the above program and parseDouble() throws NumberFormatException.
Exception in thread "main" java.lang.NumberFormatException: For input string: "5-354"
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(Unknown Source)
at java.base/java.lang.Double.parseDouble(Unknown Source)
at StringToDouble.main(StringToDouble.java:12)
NullPointerException when the String is null
If null is passed to Double.parseDouble(), the method throws NullPointerException.
Null String example with Double.parseDouble()
/**
* Java Program - Convert String to Double
*/
public class StringToDouble {
public static void main(String[] args) {
//a string
String str = null;
//convert string to double
double n = Double.parseDouble(str);
System.out.print(n);
}
}
Run the above program and parseDouble() throws NullPointerException.
Exception in thread "main" java.lang.NullPointerException
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(Unknown Source)
at java.base/java.lang.Double.parseDouble(Unknown Source)
at StringToDouble.main(StringToDouble.java:12)
Handle invalid String-to-double input with try-catch
When the input can come from a user, file, form, or external source, validate null separately and handle NumberFormatException for malformed numeric text. The existing example below catches both possible exceptions. See Java Try Catch for the exception-handling syntax.
/**
* Java Program - Convert String to Double
*/
public class StringToDouble {
public static void main(String[] args) {
//a string
String str = "8.561253652147";
double n = 0;
try {
//convert string to double
n = Double.parseDouble(str);
} catch (NumberFormatException e) {
System.out.println("Check the string. Not a valid double value.");
} catch (NullPointerException e) {
System.out.println("Check the string. String is null.");
}
System.out.print(n);
}
}
If returning a default value such as 0 could be confused with a real input value, consider returning null, an OptionalDouble, or reporting the validation error to the caller instead.
2. Convert string to Double object using Double.valueOf()
Use Double.valueOf(str) when you need a Double wrapper object. If you assign its result to a primitive double, Java automatically unboxes the object.
Java program using Double.valueOf()
/**
* Java Program - Convert String to Double
*/
public class StringToDouble {
public static void main(String[] args) {
String str = "8.561253652147";
double n = 0;
try {
//convert string to double
n = Double.valueOf(str);
} catch (NumberFormatException e) {
System.out.println("Check the string. Not a valid double value.");
} catch (NullPointerException e) {
System.out.println("Check the string. String is null.");
}
System.out.print(n);
}
}
Like Double.parseDouble(), Double.valueOf() throws NullPointerException for a null string and NumberFormatException when the string is not a parsable floating-point value.
3. Legacy String-to-Double conversion using the Double(String) constructor
Note: The Double(String) constructor is deprecated. Use Double.parseDouble() for a primitive double or Double.valueOf() for a Double object in new code.
The following existing example shows the older constructor-based approach for legacy code.
Legacy Java program using new Double(String)
/**
* Java Program - Convert String to Double
*/
public class StringToDouble {
public static void main(String[] args) {
try {
String value = "-92.26523775807";
Double d = new Double(value);
System.out.print(d);
} catch (NumberFormatException e) {
System.out.println("Check the string. Not a valid double value.");
} catch (NullPointerException e) {
System.out.println("Check the string. String is null.");
}
}
}
Convert a Java String to double with 2 decimal places
A double stores a numeric floating-point value; it does not store a fixed number of decimal places. If you need two decimal places for display, parse the string first and then format the number as text.
import java.util.Locale;
double value = Double.parseDouble("12.3456");
String formatted = String.format(Locale.ROOT, "%.2f", value);
System.out.println(formatted);
12.35
If the requirement is to round a numeric result rather than only format its display, apply an explicit rounding rule appropriate to the application. For exact decimal arithmetic, especially values such as currency, consider BigDecimal instead of double.
String to double precision and scientific notation
Java double uses binary floating-point representation, so many decimal fractions cannot be represented exactly. Converting a decimal string to double can therefore involve rounding to the nearest representable value.
A double also does not remember whether the original string used ordinary decimal notation or exponential notation. If you need to preserve the exact decimal text or always print a non-exponential representation, keep the original string or use an appropriate decimal type and formatting step rather than relying on the double value itself.
Which Java String-to-double method should you use?
Use Double.parseDouble() for the usual String-to-double conversion. Use Double.valueOf() only when a Double object is needed. Avoid the deprecated Double(String) constructor in new code, and handle null or malformed input when the string is not fully controlled by your program.
In this Java Tutorial, we learned how to convert a String to a double value in Java using Double.parseDouble() and Double.valueOf(), how parsing errors occur, and how decimal formatting differs from the numeric conversion itself.
TutorialKart.com