How to convert a string to a float in Python

Learn how to convert a string to a float in Python. Explore different methods, tips, real-world uses, and common error debugging.

How to convert a string to a float in Python
Published on: 
Thu
Feb 5, 2026
Updated on: 
Sun
Apr 5, 2026
The Replit Team

You'll often need to convert strings to floating-point numbers in Python, especially with data from files or user input. The built-in float() function makes this process simple.

In this article, we'll cover techniques for this conversion, including practical tips for real-world applications. You'll also find advice to debug common errors and ensure your code runs smoothly.

Using the float() function

string_number = "42.5"
float_number = float(string_number)
print(f"Original string: {string_number}")
print(f"Converted float: {float_number}")
print(f"Type: {type(float_number)}")--OUTPUT--Original string: 42.5
Converted float: 42.5
Type: <class 'float'>

This example shows the most direct way to handle string-to-float conversion. The float() function takes the string "42.5" and returns its floating-point equivalent. This process succeeds because the string contains characters that Python recognizes as a valid number.

The final print() statement uses the type() function to confirm the data type has changed. As the output <class 'float'> shows, the variable float_number now holds a float, successfully converting it from the original string.

Standard conversion techniques

Beyond the simple float() conversion, you'll need techniques to handle potential errors, work with different string formats, and process multiple values at once.

Handling conversion errors with try-except

def safe_float_conversion(string_value):
try:
return float(string_value)
except ValueError:
return None

print(safe_float_conversion("42.5"))
print(safe_float_conversion("invalid"))--OUTPUT--42.5
None

Not all strings can be converted to floats. If you pass a non-numeric string like "invalid" to float(), Python raises a ValueError and stops your program. To prevent this, you can wrap the conversion in a try-except block, which is a standard way to handle potential errors gracefully. You can also check if a string is a number before attempting conversion.

  • The try block attempts the risky operation—in this case, float(string_value).
  • If a ValueError occurs, the except block catches it and returns None, allowing your code to continue running without a crash.

Converting strings with special characters

price = "$1,234.56"
clean_price = price.replace("$", "").replace(",", "")
float_price = float(clean_price)
print(f"Original price: {price}")
print(f"Converted price: {float_price}")--OUTPUT--Original price: $1,234.56
Converted price: 1234.56

Real-world data is often messy. A string like "$1,234.56" will cause a ValueError because float() doesn't understand currency symbols or commas. The solution is to clean the string before converting it.

  • You can use the string's replace() method to strip unwanted characters.
  • Chaining these methods, like price.replace("$", "").replace(",", ""), lets you remove multiple characters in a single, readable line.

Once the string contains only numbers and a decimal point, float() works as expected.

Converting multiple strings using map() and list comprehension

string_numbers = ["10.5", "20.3", "30.1", "40.9"]
# Using map
float_numbers_map = list(map(float, string_numbers))
# Using list comprehension
float_numbers_comp = [float(num) for num in string_numbers]
print(float_numbers_map)--OUTPUT--[10.5, 20.3, 30.1, 40.9]

When you need to convert an entire list of strings, Python offers a couple of elegant solutions. Both map() and list comprehensions let you apply the float() function to every item in your list efficiently, saving you from writing a manual loop. To learn more about this powerful function, check out our detailed guide on the map function in Python.

  • The map() function applies float() to each string, creating a map object that you can turn into a list with list().
  • A list comprehension—[float(num) for num in string_numbers]—achieves the same result with a syntax many find more direct and readable.

Both methods are highly efficient and common in Python code.

Advanced conversion techniques

While standard methods work for clean data, real-world strings often require advanced techniques to handle international formats or extract numbers from surrounding text.

Handling international number formats

def convert_international_format(number_str):
# Convert European format (1.234,56) to US format (1234.56)
if "," in number_str and "." in number_str:
number_str = number_str.replace(".", "").replace(",", ".")
# Convert format with just comma as decimal (1234,56)
elif "," in number_str:
number_str = number_str.replace(",", ".")
return float(number_str)

print(convert_international_format("1.234,56")) # European format
print(convert_international_format("1234,56")) # Alternative format--OUTPUT--1234.56
1234.56

Number formats aren't universal. Many regions use a comma for the decimal point, which causes a ValueError with Python's standard float() function. This code handles these differences by first normalizing the string before conversion.

  • It checks for the common European format like "1.234,56", removing the thousands separator and swapping the decimal comma for a period.
  • The elif block then catches formats that only use a comma for the decimal, like "1234,56".

By replacing characters to match the format Python expects, the conversion succeeds without errors.

Extracting and converting numbers with re

import re

text = "The price is somewhere between $42.50 and $50.75"
# Extract all numbers with a decimal point
numbers = re.findall(r'\d+\.\d+', text)
# Convert to floats
float_numbers = [float(num) for num in numbers]
print(float_numbers)--OUTPUT--[42.5, 50.75]

When numbers are embedded within text, you can use Python's built-in re module to extract them with regular expressions. This approach lets you find values that match a specific pattern, even if they're surrounded by other characters. For more comprehensive pattern matching techniques, see our guide on using regex in Python.

  • The function re.findall() searches a string and returns a list of all matching text.
  • The pattern r'\d+\.\d+' is a regular expression that finds sequences of digits separated by a decimal point.
  • Once you have a list of number strings, you can convert them to floats using a list comprehension.

Creating a custom converter class

class FloatConverter:
def __init__(self, default=None, strip_chars="$£€¥ "):
self.default = default
self.strip_chars = strip_chars

def convert(self, value):
if not value:
return self.default
for char in self.strip_chars:
value = value.replace(char, "")
value = value.replace(",", ".")
try:
return float(value)
except ValueError:
return self.default

converter = FloatConverter(default=0.0)
print(converter.convert("$42.50"))
print(converter.convert("€ 1,234"))
print(converter.convert("invalid"))--OUTPUT--42.5
1234.0
0.0

For complex or repeated conversions, you can create a custom class. This FloatConverter bundles all the cleaning logic into a reusable tool. It’s initialized with a default value for errors and a set of characters to strip from strings, making it highly configurable for your specific needs.

  • The convert() method first removes any characters defined in strip_chars, such as currency symbols or spaces.
  • It then replaces commas with periods to handle different regional formats.
  • Finally, it attempts the conversion inside a try-except block, returning the default value if the string is invalid.

Move faster with Replit

Learning individual techniques is a great start, but Replit helps you move faster from practice to production. It's an AI-powered development platform where all Python dependencies come pre-installed, so you can skip setup and start coding instantly.

Instead of piecing together functions, you can use Agent 4 to build complete applications. Describe the tool you want, and the Agent will handle the code, databases, APIs, and deployment. You could build practical tools that use the conversion techniques from this article:

  • A financial data parser that cleans raw price strings of currency symbols and commas before converting them to floats for analysis.
  • A log analysis utility that uses regular expressions to find and extract numerical metrics from unstructured text files.
  • A universal number converter that correctly processes international formats by swapping decimal commas for periods before conversion.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even after a successful conversion, you might face subtle issues with precision, comparisons, and unexpected invalid values when using the float() function.

Debugging precision issues with float() calculations

Floating-point math can be tricky. Computers store these numbers in a way that introduces tiny rounding errors, causing issues with comparisons using ==. The code below shows a simple addition that doesn't behave exactly as you might expect.

price1 = float("10.1")
price2 = float("10.2")
total = price1 + price2
print(f"Total: {total}")
print(f"Expected: 20.3")
print(f"Equal check: {total == 20.3}")

Because the binary representations of 10.1 and 10.2 are imprecise, their sum isn't exactly 20.3. This causes the == check to return False. The code below shows how to compare floats correctly.

price1 = float("10.1")
price2 = float("10.2")
total = price1 + price2
print(f"Total (formatted): {total:.1f}")
print(f"Equal check (rounded): {round(total, 1) == 20.3}")

To fix the comparison, you can round the result before checking for equality. The round() function adjusts the float to a specific number of decimal places, removing the tiny precision errors. This ensures that round(total, 1) correctly evaluates to 20.3, making the comparison True. You'll want to keep an eye on this whenever you're working with financial data or any calculations where exact comparisons are critical.

Troubleshooting float() comparison problems

Directly comparing floats with the == operator often leads to surprising outcomes. Because of how computers store these numbers, simple arithmetic can fail equality checks that seem logically correct. The following code demonstrates a classic example of this behavior.

result = float("0.1") + float("0.2")
expected = 0.3
print(f"Result: {result}")
print(f"Equal to 0.3? {result == expected}")

The code adds 0.1 and 0.2, but the result isn't precisely 0.3 due to floating-point representation. This subtle inaccuracy means the comparison result == expected returns False. The following example shows a safer approach for these comparisons.

import math

result = float("0.1") + float("0.2")
expected = 0.3
print(f"Result: {result}")
print(f"Close to 0.3? {math.isclose(result, expected, abs_tol=1e-10)}")

A better approach is to use the math.isclose() function. It checks if two floats are "close enough" by comparing them within a specified tolerance, which reliably handles the tiny precision errors that cause direct equality checks with == to fail. You'll want to use this function anytime you're comparing floats, especially in financial calculations or scientific applications where accuracy is key.

Handling invalid values when using float()

When you're converting a list of strings, a single invalid value can stop your entire program. The float() function will raise a ValueError as soon as it hits a string it can't parse, like "invalid". The code below demonstrates this issue.

values = ["10.5", "invalid", "20.3", "30"]
converted = []

for value in values:
converted.append(float(value))

print(f"Converted values: {converted}")

The loop processes items in order, but the entire script crashes when it reaches "invalid". This stops the conversion before it can process the remaining valid numbers. The code below shows how to fix this.

values = ["10.5", "invalid", "20.3", "30"]
converted = []

for value in values:
try:
converted.append(float(value))
except ValueError:
converted.append(None)

print(f"Converted values: {converted}")

To prevent a single bad value from halting your program, wrap the conversion in a try-except block. This allows the loop to continue even when it encounters a non-numeric string. Instead of crashing with a ValueError, the code catches the error and appends None to your list. For comprehensive error handling techniques, see our guide on try and except in Python.

This approach is crucial when processing data from external sources like files or APIs, where you can't guarantee every value will be clean and valid.

Real-world applications

Moving past potential errors, you can use these conversion skills in real-world applications like calculating e-commerce discounts and analyzing temperature data, especially when combined with AI coding.

Calculating discounts with float() in e-commerce

Applying a sale discount in an e-commerce app is a practical task where you'll need to convert formatted price strings into floats to perform the necessary calculations.

def apply_discount(price_str, discount_percent):
price = float(price_str.replace("$", ""))
discounted_price = price * (1 - discount_percent/100)
return f"${discounted_price:.2f}"

original_prices = ["$129.99", "$24.50", "$9.99"]
discount = 25 # 25% discount

for price in original_prices:
print(f"{price} with {discount}% off: {apply_discount(price, discount)}")

The apply_discount function streamlines the entire calculation. It prepares the price string for math by removing the $ symbol before converting it to a float.

  • The core logic calculates the final price using the formula price * (1 - discount_percent/100).
  • Before returning, it formats the result back into a currency string with two decimal places using an f-string, like f"${discounted_price:.2f}".

The loop then efficiently applies this logic to every price in the list, demonstrating a practical, reusable function.

Converting and analyzing temperature data with float()

You'll often need to convert strings to floats when standardizing data from different measurement systems, like converting a mix of Fahrenheit and Celsius temperatures before analyzing them.

mixed_readings = ["22.5°C", "98.6°F", "37°C", "68.2°F"]

def convert_to_celsius(reading):
value = float(reading.rstrip("°CF"))
if reading.endswith("°F"):
return (value - 32) * 5/9
return value

celsius_readings = [convert_to_celsius(temp) for temp in mixed_readings]
print(f"Converted temperatures (°C): {[round(temp, 1) for temp in celsius_readings]}")
print(f"Average temperature: {sum(celsius_readings)/len(celsius_readings):.1f}°C")

This function is a great example of how to standardize data from different sources. The convert_to_celsius function is designed to handle strings ending in either °C or °F. For the reverse operation, see our guide on converting Celsius to Fahrenheit.

  • It first strips the unit symbols using rstrip("°CF") before converting the remaining number string to a float.
  • An if statement then checks if the temperature was in Fahrenheit and applies the conversion formula only when necessary.

A list comprehension processes all the mixed readings, creating a uniform list of Celsius values. This allows you to easily perform calculations like finding the average temperature.

Get started with Replit

Now, turn these techniques into a real tool. Describe what you want to Replit Agent, like "a currency converter for messy price strings" or "a simple web-based tip calculator."

The Agent will write the code, test for errors, and deploy your application for you. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.