Convert a Java String to Double: Syntax and Pitfalls
How to convert a Java string to double using Double.parseDouble and Double.valueOf, including NumberFormatException handling and locale-related pitfalls.

Converting a Java string to double is typically a single method call, but the surrounding details determine whether that call succeeds in production. The standard approach uses Double.parseDouble(String), yet many real-world failures come from locale-dependent number formats, trailing whitespace, or null inputs. This article focuses on the mechanics of Double.parseDouble and Double.valueOf, how to handle invalid input, and how to avoid the conversion pitfalls that appear when parsing user-provided or external data.
How Double.parseDouble Works
The primary method for converting a string to a double is Double.parseDouble. It accepts a decimal floating-point string: an optional sign, decimal digits, an optional decimal point, an optional exponent introduced by e or E, and the special tokens NaN, Infinity, and -Infinity. It returns the closest double value that can represent the textual number.
String input = "42.5";
double result = Double.parseDouble(input);
System.out.println(result); // 42.5The method accepts leading and trailing whitespace, but it does not accept an empty string or a string that contains only whitespace. Valid inputs include values like "1e3", "-0.5", "NaN", "Infinity", and "-Infinity".
double scientific = Double.parseDouble("1e3"); // 1000.0
double negative = Double.parseDouble("-0.5"); // -0.5
double notANumber = Double.parseDouble("NaN"); // NaN
double infinity = Double.parseDouble("Infinity"); // InfinityA common misunderstanding is that parseDouble accepts decimal separators other than the dot. It does not. The string must use the period as the decimal separator and the sign prefix if present. A string such as "1,5" will throw a NumberFormatException.
Using Double.valueOf for Conversion
The Double class also provides a static factory method Double.valueOf(String). Unlike parseDouble, which returns the primitive double, valueOf returns a Double instance. For most practical purposes the numeric conversion is identical, and both methods reject malformed numeric strings with NumberFormatException; null input causes NullPointerException.
Double wrapper = Double.valueOf("3.14");Because valueOf returns an object, it is useful when you need a Double type, for instance when inserting into a collection that requires a reference type. If you need a primitive, use parseDouble so you do not create an unnecessary Double object and the intent remains explicit.
The two methods have the same parsing behavior, so the choice is mostly about the return type. For simple conversions, parseDouble is the more direct option.
Handling NumberFormatException and Null Inputs
When the string is malformed, parseDouble throws NumberFormatException. This is a runtime exception, so the compiler does not force you to handle it. If it is not caught, the exception will propagate and can terminate the current thread. For any input that is not a hard-coded literal, you should catch the exception and decide how to proceed.
public double safeParse(String value) {
if (value == null) {
throw new IllegalArgumentException("Input must not be null");
}
try {
return Double.parseDouble(value);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid double: " + value, e);
}
}Passing null to parseDouble also results in a NullPointerException in current Java implementations, not a NumberFormatException. Checking for null separately avoids ambiguity about the cause of the failure.
When a conversion failure is not exceptional for your use case, you can return a default value instead of throwing. The pattern below is common in configuration loaders and data-cleaning pipelines.
public double parseOrDefault(String value, double defaultValue) {
try {
return Double.parseDouble(value);
} catch (NumberFormatException | NullPointerException e) {
return defaultValue;
}
}Catching both exceptions covers null and malformed strings. The default value should be chosen so that the rest of the program can proceed meaningfully.
Locale Issues: Why "1,5" Fails
A frequent source of failures is using a string that was formatted with a locale that uses a comma as the decimal separator. parseDouble is locale-independent and always expects a dot. If you parse a string like "3,14" directly, it throws NumberFormatException.
If the string intentionally uses a comma as the decimal separator, you need to normalize it before parsing. The simplest approach is to replace the comma with a dot, but only if you are certain the format uses a comma and not a thousands separator.
String raw = "3,14";
double value = Double.parseDouble(raw.replace(',', '.'));The replace method replaces all occurrences, so a string like "1,234,567" would become "1.234.567", which is not a valid double literal. Distinguishing a decimal comma from a thousands separator requires context about the source of the string. There is no general solution; you have to know the format of the input data.
For parsing user input according to a specific locale, the java.text.NumberFormat class is a more appropriate tool than reimplementing locale rules with replace.
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
NumberFormat germanFormat = NumberFormat.getInstance(Locale.GERMANY);
try {
Number parsed = germanFormat.parse("3,14");
double value = parsed.doubleValue();
} catch (ParseException e) {
// handle parse error
}NumberFormat also respects the grouping separators of the locale, so it can correctly parse "1.234,56" for a German locale. However, the parse method returns a Number object and does not consume the entire string, so trailing characters are ignored. If you need to validate that the entire string is numeric, you may need additional checks.
For most programmatic conversions where the data format is known and uses a dot, Double.parseDouble remains the simplest and most efficient option.
Formatting a Double Back to a String
After converting a string to a double, you often need to format it back to a string for display or persistence. Simply calling Double.toString or concatenating with a string can produce more digits than you expect, especially for values that cannot be represented exactly in binary floating point.
double value = Double.parseDouble("0.1");
System.out.println(String.valueOf(value)); // 0.1
System.out.println(value + 0.2); // 0.30000000000000004The string "0.1" is not exactly representable as a binary double, but Double.toString produces the shortest string that uniquely identifies the double value. That is why 0.1 prints as 0.1. The arithmetic result 0.30000000000000004 is a consequence of accumulated floating-point error.
When you need a specific number of decimal places, use String.format or DecimalFormat.
double doubleValue = 3.14;
String formatted = String.format(java.util.Locale.US, "%.2f", doubleValue);Using an explicit locale in String.format avoids relying on the JVM's default locale. Without a locale, formatting uses the default locale of the JVM, which can insert a comma as the decimal separator on some systems. That behavior can break downstream parsing, so it is safer to specify a locale explicitly.
Performance and Maintainability Considerations
In performance-sensitive code, Double.parseDouble is a good choice because it returns a primitive and does not allocate a Double object. Double.valueOf creates a wrapper object, which is unnecessary if all you need is a primitive. For parsing a single configuration value, the difference is negligible; for batch processing many strings, using parseDouble avoids creating many short-lived objects.
The NumberFormat path does more work: it performs locale-aware parsing and handles grouping separators. Use it only when locale handling is essential.
From a maintainability perspective, keeping conversion logic in a single utility method with a clear name makes the code easier to review and test. Instead of scattering Double.parseDouble calls with different exception handling across the codebase, centralize the parsing policy.
public final class DoubleParser {
private DoubleParser() {}
public static double parseStrict(String value) {
if (value == null) {
throw new IllegalArgumentException("value must not be null");
}
return Double.parseDouble(value);
}
}This wrapper gives you a natural place to add truncation, locale normalization, or logging without touching every call site.
Advanced: Parsing Scientific Notation and Special Values
parseDouble supports scientific notation, which is useful when your input comes from a file or API that uses exponent formats. Strings like "1.5E-10", "7e3", and "-2.5E+2" are all valid. However, the exponent marker must be e or E, and the exponent itself must be an integer with an optional sign.
double value = Double.parseDouble("1.5E-10"); // 1.5E-10Special values "NaN", "Infinity", and "-Infinity" also parse successfully. This can be a problem if your application does not expect non-finite values. After conversion, you can check with Double.isFinite to reject non-finite results.
public double parseFiniteOrThrow(String value) {
double parsed = Double.parseDouble(value);
if (!Double.isFinite(parsed)) {
throw new IllegalArgumentException("Non-finite value: " + value);
}
return parsed;
}This protects downstream arithmetic, division, or storage from values that cannot be represented normally.
A subtle behavior is that parseDouble accepts only decimal numeric syntax, not every literal form that appears in Java source code. For example, "0x1.8p1", a valid hexadecimal floating-point literal in Java, is not accepted by parseDouble.
For the vast majority of use cases, the conversion of a string to a double is straightforward. The challenges appear when the input format varies, when locale-specific separators are involved, or when you need to distinguish inexact arithmetic from a parsing failure. By choosing the right method and validating the result, you can make the conversion predictable and safe for production environments.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.