Report this

What is the reason for this report?

How to Convert String to Float in Python: Complete Guide with Examples

Updated on July 10, 2025
How to Convert String to Float in Python: Complete Guide with Examples

Introduction

In this article, we’ll show you how to reliably convert a string to a float in Python using the built-in float() function. We’ll start with the fundamentals, covering how to handle various formats like integers and scientific notation, before moving on to the most essential skill: writing resilient code. You’ll learn how to use a try-except block to gracefully handle a ValueError from non-numeric input. From there, we’ll tackle practical, real-world challenges like cleaning strings with currency symbols and converting international numbers that use commas as decimals.

By the end, you’ll understand the best practices for handling any string-to-float conversion task.

Key takeaways

  • Python’s built-in float() function handles most string-to-float conversions, including integers, decimals, negative numbers, scientific notation, and strings with leading/trailing whitespace.
  • Wrap float() conversions in try-except blocks to catch ValueError exceptions from invalid strings like "hello" or empty strings, preventing program crashes.
  • Use string replacement methods (remove commas, replace decimal separators) or Python’s locale module to convert European-style numbers like "1.234,56" to standard format.
  • float(None) raises a TypeError, not ValueError; so explicitly check for None values before attempting conversion to avoid different exception types.
  • Remove unwanted characters like currency symbols, thousands separators, and whitespace using string methods like .strip() and .replace() before calling float().
  • Build utility functions like safe_to_float() that handle common edge cases (None, empty strings, invalid input) and return sensible defaults to make your code more maintainable and robust.

Understanding String to Float Conversion in Python

In Python, you’ll often encounter data as a string of text, even when it represents a number. For instance, when a user types “19.99” into an input field or you read data from a file, it’s initially treated as text. String to float conversion is the process of turning that text representation of a number into an actual numeric type called a float. This allows you to perform mathematical operations on it.

You might wonder why is this conversion so important? Simply put, you can’t do math with text. Trying to add, subtract, or multiply strings like “50.5” and “10.2” will result in an error or unexpected behavior. To treat these values as the numbers they represent, you must first convert them into a numeric type, like a float. This process, known as type casting or type conversion, is a fundamental task in any data-driven application.

This conversion is essential in many real-world scenarios, including:

  • Handling User Input: Getting numbers from users for calculations, such as in a tip calculator or a financial application.
  • Data Processing: Parsing numerical data from files like CSVs, JSON, or text files where numbers are often stored as strings.
  • Web Scraping: Extracting product prices, ratings, or other numerical data from websites, which are always retrieved as text.
  • API Integration: Receiving data from external APIs where numerical values are sometimes formatted as strings.

Mastering this simple conversion is a key step in building robust and effective Python applications.

Prerequisites

In order to complete this tutorial, you will need:

This tutorial was tested with Python 3.11.13.

How to Use float() for Basic Conversions in Python

Python gives you a straightforward, built-in function to perform this task: float(). This function is the primary and most Pythonic way to convert a string into a floating-point number.

The syntax is simple. You just pass the string you want to convert inside the parentheses.

float(your_string)

Let’s see an example. The float() function can handle strings that represent positive numbers, negative numbers, and even whole numbers.

1. Converting a Standard Numeric String

This is the most common use case: a string containing a number with a decimal.

price_string = "24.99"
print("Type before conversion:", type(price_string))

price_float = float(price_string)
print("Type after conversion:", type(price_float))

Output:

Type before conversion: <class 'str'>

Type after conversion: <class 'float'>

As you can see, the string "24.99" was successfully converted to the float 24.99, and its type is now float.

2. Converting a String Representing an Integer or Negative Number

Whether your string represents an integer, or a negative value, float() processes it correctly.

# String representing an integer
int_string = "350"
print(f"'{int_string}' becomes: {float(int_string)}")

# String representing a negative decimal
neg_string = "-45.93"
print(f"'{neg_string}' becomes: {float(neg_string)}")

Output:

'350' becomes: 350.0
'-45.93' becomes: -45.93

Note: If you are not familiar with string formatting using f prefix, please read f-strings in Python.

3. Handling Leading/Trailing Whitespace

Often, data from files or user input comes with extra spaces. Thankfully, float() automatically handles leading and trailing whitespace.

reading_string = "  -99.5  "
reading_float = float(reading_string)

print(reading_float)

Output:

-99.5

The float() function ignored the extra spaces and correctly converted the string to a negative float. In the next section, we’ll cover what happens when you try to convert a string that isn’t a valid number.

Converting Scientific Notation

Scientific notation (e-notation) is a way to express very large or very small numbers. Python’s float() function understands this format without any extra work.

For example, the string "1.5e10" represents 1.5 times 10 to the power of 10.

scientific_string = "1.5e10"
scientific_float = float(scientific_string)

print(f"'{scientific_string}' becomes: {scientific_float}")
print(type(scientific_float))

Output:

'1.5e10' becomes: 15000000000.0
<class 'float'>

The float() function effortlessly handles these common formats, making your conversion tasks much simpler.

Handling Errors: The ValueError and Safe Conversions

What happens when you try to convert a string that isn’t a number, like "hello" or an empty string ""? If you’re not careful, your program will crash. In this section, we’ll cover how to handle these situations gracefully.

Understanding the ValueError Exception

When you pass an invalid string (one that cannot be interpreted as a number) to the float() function, Python raises a ValueError.

Let’s see what happens when we try to convert non-numeric text:

invalid_string = "not a number"

price_float = float(invalid_string)

print(price_float)

Running this code stops execution and throws a ValueError with a message telling you it could not convert the string to a float.

Using try-except Blocks for Safe Conversion

To prevent crashes, you should wrap your conversion code in a try-except block. This is the standard Pythonic way to handle exceptions in Python.

The logic is simple:

  • The try block contains the code that might fail (the “risky” operation).
  • The except block contains the code that runs only if an error occurs in the try block.

This allows you to catch the ValueError and handle it gracefully instead of letting your program terminate.

input_string = "not a number"
value_float = 0.0 

try:
  value_float = float(input_string)
  print("Conversion successful!")
except ValueError:
  print(f"Could not convert '{input_string}'.")

print(f"The final float value is: {value_float}")

Output:

Could not convert 'not a number'.
The final float value is: 0.0

As you can see, the program didn’t crash. By anticipating the error, we provided a fallback plan and maintained control.

Handling Empty Strings and None Values

The two most common edge cases are empty strings ("") and None values.

  • Empty Strings: An empty string is not a valid number, so float("") will also raise a ValueError. The try-except block we just created handles this perfectly.
  • None Values: Trying to convert None is a different kind of error. float(None) will raise a TypeError, not a ValueError. If your code encounters None, you should check for it explicitly before trying the conversion.

Here is a function that handles invalid strings, empty strings, and None:

def safe_to_float(value):
  if value is None:
    return 0.0
  try:
    return float(value)
  except (ValueError, TypeError):
    return 0.0

# Test cases 
print(f"'123.45' becomes: {safe_to_float('123.45')}")
print(f"'hello' becomes: {safe_to_float('hello')}")
print(f"An empty string '' becomes: {safe_to_float('')}")
print(f"None becomes: {safe_to_float(None)}")

Output:

'123.45' becomes: 123.45
'hello' becomes: 0.0
An empty string '' becomes: 0.0
None becomes: 0.0

Handling International Number Formats

Numeric formats can change depending on the region. In many parts of North America and the UK, a number might be written as 1,234.56. However, in much of Europe and other regions, the roles are swapped, and the same number is written as 1.234,56.

Python’s float() function, by default, only recognizes a period (.) as a decimal separator. Trying to convert "1.234,56" will result in a ValueError. Here are two ways to handle this.

1. The String Replacement Method

For most cases, the simplest solution is to manipulate the string to a format that Python understands before you try to convert it. This involves two steps:

  1. Remove the thousands separators.
  2. Replace the comma decimal separator with a period.
de_string = "1.234,56"

temp_string = de_string.replace(".", "")

standard_string = temp_string.replace(",", ".")

value_float = float(standard_string)

print(f"Original string: '{de_string}'")
print(f"Standardized string: '{standard_string}'")
print(f"Converted float: {value_float}")

In this example, we’ll use a European-formatted number string. First, we remove the '.' thousands separator. Then, we replace the ',' decimal separator with a '.'. Finally, we convert the standardized string.

Output:

Original string: '1.234,56'
Standardized string: '1234.56'
Converted float: 1234.56

This method is simple, effective, and doesn’t require any special libraries.

2. Using the locale Module

For applications that need to handle different international formats dynamically, Python’s locale module is the right tool. This module can interpret numbers according to a specific region’s conventions.

To use it, you first set the “locale” (region) and then use the locale.atof() function (ASCII to float) for the conversion.

import locale

de_string = "1.234,56"

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

    value_float = locale.atof(de_string)
    
    print(f"Successfully converted '{de_string}' to {value_float}")

except locale.Error:
    print("Locale 'de_DE.UTF-8' not supported on this system.")
finally:
    locale.setlocale(locale.LC_NUMERIC, '')

We start by setting the locale to German (de_DE) with UTF-8 encoding.

Note: The 'de_DE.UTF-8' locale must be supported by your OS.

Then, we use locale.atof() to convert the string in a locale-aware way.

Output:

Successfully converted '1.234,56' to 1234.56

The locale module is the more robust and “correct” solution for building internationalized applications. For quick, one-off scripts, the string replacement method is often sufficient.

Best Practices

To ensure your code is robust, readable, and error-free, keep these best practices in mind when converting strings to floats in Python.

  • Always Wrap External Input in a try-except Block: This is the most critical rule. Data from users, files, or APIs is unpredictable. A try-except ValueError block will prevent your program from crashing due to a single invalid string and allow you to handle the error gracefully.
  • Clean Your Strings Before Conversion: Don’t pass messy strings directly to float(). First, use string methods like .strip() to remove leading/trailing whitespace and .replace() to eliminate unwanted characters. For more advanced cleaning, you can review our article on common string manipulation techniques.
  • Assign a Sensible Default Value: When a conversion fails inside an except block, decide on a fallback plan. Is it better to skip the entry, or should you assign a default value like 0.0 or None? This ensures your program can continue running with predictable data.
  • Create a Helper Function for Repetitive Conversions: If you perform the same conversion logic in multiple places, encapsulate it in a reusable function (like the safe_to_float() example earlier). This makes your code cleaner, easier to read, and simpler to update.
  • Be Aware of International Number Formats: If your application processes data from different parts of the world, remember that decimal separators can be commas instead of periods. Use the string replacement method for simple cases or the locale module for more complex, locale-aware applications.
  • Stick with float() for Simplicity: For all standard conversions, the built-in float() function is the most direct, readable, and Pythonic tool for the job. Avoid overly complex solutions when a simple one works perfectly.

Frequently Asked Questions (FAQs)

1. How do I convert a string to float in Python?

The simplest way is to use Python’s built-in float() function. You pass the numeric string as an argument, and it returns the corresponding float.

For example, float("123.45") will return 123.45.

2. What happens if the string isn’t a valid float?

Python raises a ValueError exception when you attempt to convert a non-numeric string using float(). For example, float("hello") will throw a ValueError: could not convert string to float: hello. Always use try-except blocks to handle this gracefully.

3. How do I convert a string with commas like “1,234.56”?

Python’s float() function doesn’t recognize comma separators by default. You need to remove commas first: float("1,234.56".replace(",", "")) or use locale-specific functions like locale.atof() after setting the appropriate locale.

4. How to convert string to a float with 2 decimal in Python?

You can’t directly convert a string to a float with a specific number of decimal places. It’s a two-step process: you first convert the string to a float, then format that float to two decimal places.

  • For Display (Get a String): Use an f-string with the :.2f format specifier. This is best for printing or showing the value in a UI.
price_string = "49.99123"
formatted_price = f"{float(price_string):.2f}"
print(formatted_price)
# Output: "49.99"
  • For Calculation (Get a Float): Use the built-in round() function. This is best if you need to use the rounded number in further math operations.
price_string = "49.99123"
rounded_price = round(float(price_string), 2)
print(rounded_price)
# Output: 49.99

5. What’s the difference between float() and int() when converting strings?

float() converts strings to floating-point numbers (decimals), while int() converts to integers. float("3.14") returns 3.14, but int("3.14") raises a ValueError. Use int(float("3.14")) to convert decimal strings to integers. This will return 3.

6. How do I handle scientific notation strings like “1.5e10”?

Python’s float() function natively supports scientific notation. float("1.5e10") correctly returns 15000000000.0. This works for both positive and negative exponents like "1.5e-3".

Conclusion

In this article, you’ve learned how to reliably convert strings to floats in Python, a fundamental skill for handling real-world data.

We started with the basics, using the built-in float() function to handle simple numeric strings, integers, and scientific notation. We then moved to the most critical aspect of robust programming: safely handling errors. You now know how to use a try-except block to catch a ValueError, ensuring your applications don’t crash when they encounter unexpected, non-numeric text.

Finally, we tackled practical, advanced scenarios. You can now clean strings by removing unwanted characters such as currency symbols, commas, whitespaces, and thousands separators, and you have the tools to correctly process international number formats that use commas as decimals. With these skills, you’re now equipped to write more versatile Python code that can handle the messy, unpredictable data you’ll encounter in any project.

To learn more about Python strings, check out the following articles:

Or check out more Python examples from our GitHub repository.

References:

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Pankaj Kumar
Pankaj Kumar
Author
See author profile

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

Manikandan Kurup
Manikandan Kurup
Editor
Senior Technical Content Engineer I
See author profile

With over 6 years of experience in tech publishing, Mani has edited and published more than 75 books covering a wide range of data science topics. Known for his strong attention to detail and technical knowledge, Mani specializes in creating clear, concise, and easy-to-understand content tailored for developers.

Category:
Tags:

Still looking for an answer?

Was this helpful?
Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.