Python: String to Float Conversion

By
Bosko Marijan
Published:
November 17, 2025
Topics:

In Python, converting strings to floats is essential when working with numeric data stored as text. This often happens when values come from user input, files, APIs, or external data sources. Since Python treats strings and numbers differently, numeric operations, like addition or comparison, will not work correctly unless the data is converted.

In this tutorial, you will learn to convert strings to floats using different methods.

Python string to float conversion - a tutorial.

Prerequisites

Convert String to Float in Python

Python offers multiple ways to convert string values into floating-point numbers. The most common and reliable method uses the built-in float() function, but there are also alternative approaches using modules like decimal, or even eval().

The sections below cover the most common string-to-float conversion methods with examples. You can test the examples in several ways:

  • In the interactive shell (e.g., typing directly in a terminal or IDLE).
  • Inside an IDE, such as VS Code or PyCharm.
  • As a Python script, which is the method used in this tutorial.

Note: Check out our in-depth article to learn more about Python data types.

Using float()

The float() function is the simplest and most direct way to convert a string into a float. It works with both integers and decimal strings, provided they are formatted correctly.

Follow the steps below:

1. Create a new file called float.py, for example with nano:

nano float.py

2. Paste the following code into the file:

value = "3.14"
num = float(value)
print(num)

If you have a list of numeric strings, you can convert them all at once:

values = ["1.2", "2.5", "3.8"]
floats = [float(v) for v in values]
print(floats)

If you want to read from a file, modify the script as follows:

with open("numbers.txt", "r") as file:
    for line in file:
        num = float(line.strip())
        print(num)

3. Save and close the script.

4. Run the script in the terminal:

python3 float.py
Converting strings to floats in Python using float.

This example converts string values into floating-point numbers and prints them on the screen.

Using decimal.Decimal

The decimal.Decimal class provides more precise control over floating-point numbers than the built-in float() function. It is handy when working with financial or scientific data where rounding errors must be avoided.

Follow the steps below:

1. Create a new file called decimal_convert.py:

nano decimal_convert.py

2. Paste the following code into the file:

from decimal import Decimal

value = "3.14"
num = Decimal(value)
print(num)

If you have a list of numeric strings, you can convert them all at once:

from decimal import Decimal

values = ["1.2", "2.5", "3.8"]
decimals = [Decimal(v) for v in values]
print(decimals)

To read and convert numbers directly from a file, modify the script as follows:

from decimal import Decimal

with open("numbers.txt", "r") as file:
    for line in file:
        num = Decimal(line.strip())
        print(num)

3. Save and close the file.

4. Run the script in the terminal:

python3 decimal_convert.py
Converting strings to floats in Python using decimal.

This example converts string values into precise decimal objects using the decimal module. Unlike float, Decimal maintains exact precision, which is ideal for handling currency, measurements, or any data where accuracy is critical.

Using ast.literal_eval()

The ast.literal_eval() function safely evaluates a string containing a Python literal, such as numbers, lists, tuples, or dictionaries. It can convert strings that represent floats into actual float objects while avoiding the security risks of using eval().

Follow the steps below:

1. Create a new file called literal_eval.py:

nano literal_eval.py

2. Paste the following code:

import ast

value = "3.14"
num = ast.literal_eval(value)
print(num)  # Output: 3.14

If you have multiple numeric strings in a list, you can evaluate each element:

import ast

values = ["1.2", "2.5", "3.8"]
floats = [ast.literal_eval(v) for v in values]
print(floats)

To read from a file and safely evaluate each line, modify the script as follows:

import ast

with open("numbers.txt", "r") as file:
    for line in file:
        num = ast.literal_eval(line.strip())
        print(num)

3. Save and close the file.

4. Run the script in the terminal:

python3 literal_eval.py
Converting strings to floats in Python using literal.eval.

This example demonstrates how ast.literal_eval() safely converts strings representing valid Python literals into their corresponding data types. It is safer than eval() as it only parses simple literals and cannot execute arbitrary code.

Using eval()

The eval() function can also convert strings into floats, but it should be used with extreme caution. Unlike ast.literal_eval(), eval() executes any Python code passed to it, which can pose serious security risks if the input comes from untrusted sources. However, in controlled environments, like quick tests or internal scripts, it can be useful.

Follow the steps below:

1. Create a new file called eval_convert.py:

nano eval_convert.py

2. Paste the following code:

value = "3.14"
num = eval(value)
print(num)

If you have a list of numeric strings, you can evaluate them all at once:

values = ["1.2", "2.5", "3.8"]
floats = [eval(v) for v in values]
print(floats)

You can also use eval() to read values from a file, but only if the file contents are fully trusted:

with open("numbers.txt", "r") as file:
    for line in file:
        num = eval(line.strip())
        print(num)

3. Save and close the file.

4. Run the script in the terminal:

python3 eval_convert.py
Converting strings to floats in Python using eval.

This example shows how eval() interprets strings as Python expressions and converts them into their corresponding data types. While it works similarly to ast.literal_eval(), it is not recommended for handling user input or external data due to potential security vulnerabilities.

Using json.loads()

The json.loads() function can convert strings that represent JSON data into Python objects. It is particularly useful when working with numeric strings embedded in JSON from APIs, web responses, or configuration files. Unlike eval(), json.loads() is safe for untrusted input as it only parses valid JSON.

1. Follow the steps below:

2. Create a new file called json_convert.py:

nano json_convert.py

3. Paste the following code into the file:

import json

value = '"3.14"'
num = json.loads(value)
print(num)

If you have multiple numeric strings in a JSON array, you can convert them all at once:

import json

values = '["1.2", "2.5", "3.8"]'
floats = [json.loads(v) for v in json.loads(values)]
print(floats)

To read numeric strings from a JSON file:

import json

with open("numbers.json", "r") as file:
    numbers = json.load(file)  # loads a JSON array from the file

    floats = [float(n) for n in numbers]
    print(floats)

3. Save and close the file.

4. Run the script in the terminal:

python3 json_convert.py
Converting strings to floats in Python using json.load.

This example shows how json.loads() can safely parse numeric strings from JSON format into Python numbers. It is especially useful for processing data from APIs, web services, or any source that outputs JSON.

Handling Locale and Formatting Differences

Some numeric strings use commas or spaces as decimal separators instead of the standard dot (.). Directly converting these strings with float() will raise a ValueError.

To handle these cases, clean the string before conversion. For example:

value = "12,34"
clean_value = value.replace(",", ".")
num = float(clean_value)
print(num)
Handling locale differences with Python.

Explanation:

  • The replace() function changes the comma to a dot, so float() can parse the string.
  • This method is simple, safe, and works for both single values and bulk conversions.
  • For larger datasets, consider wrapping this logic in a helper function to standardize input consistently.

This approach can also be applied to lists or file input using list comprehensions or loops, ensuring your data is correctly formatted before conversion.

Alternative Ways to Convert String to Float in Python

When working with large datasets or numerical arrays, using specialized libraries like pandas or NumPy makes string-to-float conversion faster and more efficient.

The sections below showcase alternative methods for converting strings to floats in Python.

Using Pandas

Pandas is a powerful library for working with tabular data. It allows you to load numeric strings into a DataFrame and convert entire columns to floats using the .astype() method. This approach is useful for processing CSV files, datasets, or structured data.

Follow the steps below to install pandas in a virtual environment and convert strings to floats:

1. Create and activate a virtual environment:

python3 -m venv venv
source venv/bin/activate
Creating and activating a virtual environment in Python.

2. Install Pandas inside the virtual environment:

pip install pandas
Installing Pandas using pip.

3. Create a new file called pandas_convert.py:

nano pandas_convert.py

4. Paste the following code into the file:

import pandas as pd

data = {"price": ["10.5", "20.7", "30.2"]}
df = pd.DataFrame(data)
df["price"] = df["price"].astype(float)
print(df)

Alternatively, use pd.to_numeric() to automatically handle conversion and errors:

df["price"] = pd.to_numeric(df["price"], errors="coerce")

The errors="coerce" parameter replaces invalid values with NaN, helping maintain clean data.

5. Save and close the file.

6. Run the script:

python3 pandas_convert.py
Converting strings to floats in Python using Pandas.

This example loads a dictionary of numeric strings into a DataFrame, converts the price column to floats, and prints the resulting table.

Using NumPy

NumPy allows efficient conversion of large string arrays to floats through vectorized operations. This is particularly useful in scientific or statistical computations.

Follow the steps below to install NumPy inside a virtual environment and convert strings to floats:

1. Create and activate a virtual environment:

python3 -m venv venv
source venv/bin/activate

2. Install NumPy inside the virtual environment:

pip install numpy
Installing NumPy with pip.

3. Create a new file:

nano convert_numpy.py

4. Paste the following code:

import numpy as np

arr = np.array(["1.1", "2.2", "3.3"])
float_arr = arr.astype(float)
print(float_arr)

5. Save and exit the file.

6. Run the file:

python3 convert_numpy.py
Converting strings to floats in Python using NumPy.

NumPy's conversion methods are optimized for performance and can handle bulk operations much faster than loops or comprehensions.

Python String to Float Conversion: Common Errors

Conversion errors usually occur due to invalid formatting, missing values, or unexpected characters in the string.

Common causes include:

  • Invalid numeric format. If the string contains letters or symbols that are not part of a valid number, Python raises a ValueError. Validate or clean the input before converting.
  • Whitespace or commas. Leading/trailing spaces are allowed, but commas are not. Remove commas or thousands separators before converting.
  • Localized decimal separators. Many locales use a comma instead of a dot. Standardize the separator to a dot to avoid errors.

To handle conversion errors gracefully, wrap conversions in try...except blocks. For example:

try:
    num = float("abc")
except ValueError:
    print("Invalid number format.")

Conclusion

This article showed how to convert strings to floats in Python. String-to-float conversion is a key part of data processing in Python, ensuring that text-based numeric values can be used for calculations and analysis.

Next, see how to reverse a list in Python, or learn about string concatenation.

Was this article helpful?
YesNo