Skip to main content

How to Convert String to Float in Python

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.

# Basic conversion
price = "19.99"
value = float(price)

print(value)
# Output: 19.99

# Whitespace is handled automatically
padded = " 42.5 "
print(float(padded))
# Output: 42.5

# Negative numbers work as expected
negative = "-273.15"
print(float(negative))
# Output: -273.15
info

The float() function only accepts strings with digits, a single decimal point, and an optional sign. Any other characters cause a ValueError.

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"

# Remove currency symbol and thousand separators
clean = raw_price.replace('$', '').replace(',', '')
value = float(clean)

print(value)
# Output: 1299.99

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."""
# Remove common currency symbols and whitespace
cleaned = re.sub(r'[$€£¥₹\s]', '', value)
# Remove thousand separators (commas)
cleaned = cleaned.replace(',', '')
return float(cleaned)

# Test with various formats
print(parse_currency("$1,299.99")) # 1299.99
print(parse_currency("€ 599,00".replace(',', '.'))) # 599.0
print(parse_currency("£2,500.00")) # 2500.0

Handle 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

# Set French locale (comma as decimal separator)
locale.setlocale(locale.LC_NUMERIC, 'fr_FR.UTF-8')

european_price = "1 234,56"
value = locale.atof(european_price)

print(value)
# Output: 1234.56
⚠ Windows Users

The locale fr_FR.UTF-8 does not work on Windows.

  • On Windows, you should use: locale.setlocale(locale.LC_NUMERIC, "French_France").
  • French numeric formatting uses a non-breaking space (\xa0) as the thousands separator.
  • Strings with a regular space like "1 234,56" will fail with locale.atof().
  • For cross-platform safety, consider replacing spaces and converting commas manually:
european_price = "1 234,56"
value = float(european_price.replace(" ", "").replace(",", "."))
print(value) # 1234.56

Compare Regional Formats​

import locale

# US format: 1,234.56
locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8')
us_value = locale.atof("1,234.56")
print(f"US format: {us_value}")
# Output: US format: 1234.56

# German format: 1.234,56
locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
de_value = locale.atof("1.234,56")
print(f"German format: {de_value}")
# Output: German format: 1234.56
warning

The locale.setlocale() function modifies global state and is not thread-safe. For web applications or multi-threaded programs, consider manual string replacement or dedicated parsing libraries.

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:
# Attempt standard conversion
return float(value.strip())
except ValueError:
# Try cleaning common formatting
try:
cleaned = value.replace('$', '').replace(',', '').strip()
return float(cleaned)
except ValueError:
return default

# Valid inputs
print(safe_float("42.5")) # 42.5
print(safe_float("$1,000.00")) # 1000.0

# Invalid inputs return default
print(safe_float("N/A")) # 0.0
print(safe_float("")) # 0.0
print(safe_float(None)) # 0.0

Validate 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

# Filter valid entries from a list
data = ["10.5", "invalid", "20.0", "", "30"]
valid_numbers = [float(x) for x in data if is_numeric_string(x)]

print(valid_numbers)
# Output: [10.5, 20.0, 30.0]

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

# Convert and filter valid prices
prices = [p for s in raw_prices if (p := parse_price(s)) is not None]

print(prices)
# Output: [19.99, 24.5, 9.99]

print(f"Total: ${sum(prices):.2f}")
# Output: Total: $54.48

Quick Reference​

Input TypeSolutionExample
Clean numberfloat(s)float("12.5")
With whitespacefloat(s)float(" 12.5 ")
Currency symbolfloat(s.replace('$', ''))"$12.50" → 12.5
Thousand separatorsfloat(s.replace(',', ''))"1,000" → 1000.0
European formatlocale.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.