Skip to content

How to Convert String to Double in Python

Learn how to convert strings to floating-point numbers in Python using float(), handle international formats with commas, and use Decimal for precise financial calculations.

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)

print(value + 1.5)

print(type(value))

Handle Scientific Notation

The float() function automatically parses scientific notation strings.

scientific = "3.14e-10"
value = float(scientific)

print(value)

print(f"{value:.15f}")

Handle Special Float Values

Python recognizes string representations of special floating-point values.

positive_inf = float("inf")
negative_inf = float("-inf")

print(positive_inf > 1e308)

nan_value = float("nan")

print(nan_value == nan_value)

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

locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')

german_number = "1.234,56"
value = locale.atof(german_number)

print(value)

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."""
    cleaned = s.replace(".", "").replace(",", ".")
    return float(cleaned)

value = parse_european_number("1.234,56")
print(value)

Use Decimal for Precise Calculations

Binary floating-point numbers cannot represent all decimal fractions exactly, leading to subtle rounding errors.

result = 0.1 + 0.2
print(result)

print(result == 0.3)

For financial calculations, scientific applications, or any context requiring exact decimal representation, use the Decimal class.

from decimal import Decimal

price = Decimal("10.05")
quantity = Decimal("3")
total = price * quantity

print(total)

print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))

Configure Decimal Precision

from decimal import Decimal, getcontext

getcontext().prec = 50

result = Decimal("1") / Decimal("7")
print(result)

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

print(safe_float("42.5"))

print(safe_float("not a number"))

print(safe_float(""))

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.

Navigation