How to Convert String to Double in Python
Python's float type implements IEEE 754 double-precision floating-point numbers, equivalent to double in C, Java, or C#. There is no separate double keyword in Python because float provides the same 64-bit precision by default.
Convert String to Float Using float()
The built-in float() function handles standard decimal notation with dot separators.
price = "12.50"
value = float(price)
print(value)
# Output: 12.5
print(value + 1.5)
# Output: 14.0
print(type(value))
# Output: <class 'float'>
Handle Scientific Notation
The float() function automatically parses scientific notation strings.
scientific = "3.14e-10"
value = float(scientific)
print(value)
# Output: 3.14e-10
print(f"{value:.15f}")
# Output: 0.000000000314000
Handle Special Float Values
Python recognizes string representations of special floating-point values.
# Infinity
positive_inf = float("inf")
negative_inf = float("-inf")
print(positive_inf > 1e308)
# Output: True
# Not a Number
nan_value = float("nan")
print(nan_value == nan_value)
# Output: False (NaN is never equal to itself)
Handle Comma Decimal Separators with locale
Many countries use commas as decimal separators (e.g., 12,50 instead of 12.50). The built-in float() function raises a ValueError on these formats. Use the locale module to parse numbers according to regional conventions.
import locale
# Set to German locale (uses comma as decimal separator)
locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
# Parse string with locale-aware function
german_number = "1.234,56"
value = locale.atof(german_number)
print(value)
# Output: 1234.56
Calling locale.setlocale() affects the entire process and is not thread-safe. For multi-threaded applications, consider manual string preprocessing instead.
Manual Comma Handling Without Locale
For simple cases or thread-safe code, preprocess the string manually.
def parse_european_number(s: str) -> float:
"""Convert European format (1.234,56) to float."""
# Remove thousand separators, replace decimal comma
cleaned = s.replace(".", "").replace(",", ".")
return float(cleaned)
value = parse_european_number("1.234,56")
print(value)
# Output: 1234.56
Use Decimal for Precise Calculations
Binary floating-point numbers cannot represent all decimal fractions exactly, leading to subtle rounding errors.
# Classic floating-point precision issue
result = 0.1 + 0.2
print(result)
# Output: 0.30000000000000004
print(result == 0.3)
# Output: False
For financial calculations, scientific applications, or any context requiring exact decimal representation, use the Decimal class.
from decimal import Decimal
# Always pass strings to Decimal for exact representation
price = Decimal("10.05")
quantity = Decimal("3")
total = price * quantity
print(total)
# Output: 30.15
# Precise comparison works correctly
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))
# Output: True
Always initialize Decimal objects from strings, not floats. Using Decimal(0.1) inherits the float's imprecision, defeating the purpose.
Configure Decimal Precision
from decimal import Decimal, getcontext
# Set precision for calculations
getcontext().prec = 50
result = Decimal("1") / Decimal("7")
print(result)
# Output: 0.14285714285714285714285714285714285714285714285714
Handle Invalid Input Safely
Always validate or handle exceptions when converting user input.
def safe_float(value: str, default: float = 0.0) -> float:
"""Safely convert string to float with fallback."""
try:
return float(value.strip())
except (ValueError, AttributeError):
return default
# Valid input
print(safe_float("42.5"))
# Output: 42.5
# Invalid input returns default
print(safe_float("not a number"))
# Output: 0.0
print(safe_float(""))
# Output: 0.0
Validate Before Conversion
import re
def is_valid_float(s: str) -> bool:
"""Check if string is a valid float format."""
pattern = r'^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$'
return bool(re.match(pattern, s.strip()))
print(is_valid_float("3.14")) # True
print(is_valid_float("-2.5e10")) # True
print(is_valid_float("12,50")) # False
print(is_valid_float("abc")) # False
Quick Reference
| Input Format | Method | Use Case |
|---|---|---|
"12.34" | float(s) | General-purpose conversion |
"3.14e-10" | float(s) | Scientific notation |
"1.234,56" | locale.atof(s) | International number formats |
"10.05" | Decimal(s) | Financial and precise calculations |
Conclusion
Use float() for general-purpose string-to-number conversion: it handles standard decimal notation and scientific formats efficiently. When processing international input with comma decimal separators, apply locale.atof() or manual string preprocessing. For financial applications or calculations requiring exact decimal precision, always use Decimal with string initialization to avoid the inherent rounding errors of binary floating-point arithmetic.