Converting strings to floating-point numbers is a common task when processing user input, reading CSV files, or parsing API responses. Real-world data often includes currency symbols, thousand separators, and regional formatting that require careful handling.
Convert Clean Strings with float()
The built-in float() function converts well-formatted numeric strings and automatically strips leading and trailing whitespace.
price = "19.99"
value = float(price)
print(value)
padded = " 42.5 "
print(float(padded))
negative = "-273.15"
print(float(negative))Clean Currency and Formatted Numbers
Real-world data frequently contains currency symbols, thousand separators, or other formatting characters. Preprocess these strings before conversion.
raw_price = "$1,299.99"
clean = raw_price.replace('$', '').replace(',', '')
value = float(clean)
print(value)Build a Reusable Cleaning Function
For production code, create a function that handles multiple formatting scenarios.
import re
def parse_currency(value: str) -> float:
"""Convert formatted currency string to float."""
cleaned = re.sub(r'[$€£¥₹\s]', '', value)
cleaned = cleaned.replace(',', '')
return float(cleaned)
print(parse_currency("$1,299.99")) # 1299.99
print(parse_currency("€ 599,00".replace(',', '.'))) # 599.0
print(parse_currency("£2,500.00")) # 2500.0Handle European Number Formats with locale
Many countries use commas as decimal separators and dots as thousand separators (e.g., 1.234,56 means 1234.56). The locale module parses these formats correctly.
import locale
locale.setlocale(locale.LC_NUMERIC, 'fr_FR.UTF-8')
european_price = "1 234,56"
value = locale.atof(european_price)
print(value)Compare Regional Formats
import locale
locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8')
us_value = locale.atof("1,234.56")
print(f"US format: {us_value}")
locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
de_value = locale.atof("1.234,56")
print(f"German format: {de_value}")Handle Conversion Errors Gracefully
User input and external data sources may contain invalid values. Always implement error handling for production code.
def safe_float(value: str, default: float = 0.0) -> float:
"""Convert string to float with error handling."""
if not value or not value.strip():
return default
try:
return float(value.strip())
except ValueError:
try:
cleaned = value.replace('$', '').replace(',', '').strip()
return float(cleaned)
except ValueError:
return default
print(safe_float("42.5")) # 42.5
print(safe_float("$1,000.00")) # 1000.0
print(safe_float("N/A")) # 0.0
print(safe_float("")) # 0.0
print(safe_float(None)) # 0.0Validate Input Before Conversion
def is_numeric_string(value: str) -> bool:
"""Check if string can be converted to float."""
try:
float(value.replace(',', '').replace('$', ''))
return True
except (ValueError, AttributeError):
return False
data = ["10.5", "invalid", "20.0", "", "30"]
valid_numbers = [float(x) for x in data if is_numeric_string(x)]
print(valid_numbers)Process Multiple Values Efficiently
When converting lists of strings, use list comprehensions with error handling.
raw_prices = ["$19.99", "$24.50", "N/A", "$9.99", ""]
def parse_price(s: str) -> float | None:
"""Parse price string, return None for invalid values."""
try:
return float(s.replace('$', '').replace(',', ''))
except ValueError:
return None
prices = [p for s in raw_prices if (p := parse_price(s)) is not None]
print(prices)
print(f"Total: ${sum(prices):.2f}")Quick Reference
| Input Type | Solution | Example |
|---|---|---|
| Clean number | float(s) |
float("12.5") |
| With whitespace | float(s) |
float(" 12.5 ") |
| Currency symbol | float(s.replace('$', '')) |
"$12.50" → 12.5 |
| Thousand separators | float(s.replace(',', '')) |
"1,000" → 1000.0 |
| European format | locale.atof(s) |
"12,50" → 12.5 |
Conclusion
Use float() directly for clean, well-formatted numeric strings. For real-world data containing currency symbols or thousand separators, preprocess with str.replace() or regular expressions. When handling international formats with comma decimal separators, the locale module provides region-aware parsing. Always implement error handling when processing external data to prevent crashes from malformed input.