Table of contents
1.
Introduction
2.
Converting String to Float
2.1.
Example 1: Basic Conversion
2.2.
Converting a string with commas
2.3.
Converting to a float list
2.4.
Converting a list of strings to float
3.
Python Program to Parse a String to a Float Using float()
4.
ValueError Exception
4.1.
Example: Handling ValueError
4.2.
Key Points
5.
Convert String to Float with Specified Decimal Points
5.1.
Example: Specifying Decimal Points
6.
Convert String to Float Using NumPy
6.1.
Example: Using NumPy for Conversion
7.
Using the str() function
8.
Frequently Asked Questions
8.1.
What happens if the string contains invalid characters during conversion?
8.2.
Can I convert a list of strings to floats without a loop?
8.3.
How do I round a float to two decimal points after conversion?
9.
Conclusion
Last Updated: Aug 22, 2025
Easy

String to Float in Python

Author Rahul Singh
0 upvote

Introduction

In Python, sometimes we need to change a string of numbers into a floating-point number, especially when we want to do math or calculations. Converting strings to float values is a common operation, especially when working with user inputs, data processing, or file operations.  A string is simply text, and a float is a number with decimals. If you have a number as a string, you can easily turn it into a float using Python’s built-in tools.

String to Float in Python

In this article, you will learn how to convert a string to a float in Python. We will cover the simple way to do it using the float() function and how to avoid common errors that can happen during this conversion.

Converting String to Float

The most simple way to convert a string to a float in Python is by using the float() function. This built-in function accepts a string containing a numerical value and converts it into a floating-point number.

Example 1: Basic Conversion

# Example of string to float conversion
num_str = "12.34"
num_float = float(num_str)
print("String:", num_str)
print("Float:", num_float)
You can also try this code with Online Python Compiler
Run Code


Output:

String: 12.34  
Float: 12.34


In this example, the string "12.34" is successfully converted into a floating-point number 12.34.

Explanation

The float() function checks whether the string contains a valid numeric representation. If valid, it converts the string into a float. If not, it raises a ValueError.

Converting a string with commas

Sometimes, you may encounter strings that represent numbers with commas as thousand separators, such as "1,000" or "3,141,592.65". To convert these strings to floats, you need to remove the commas first. For example:

string_with_commas = "1,000,000.50"
string_without_commas = string_with_commas.replace(",", "")
float_num = float(string_without_commas)
print(float_num)  
You can also try this code with Online Python Compiler
Run Code


Output: 

1000000.5


In this example, we start with a string "1,000,000.50" that contains commas. We use the replace() method to remove the commas by replacing them with an empty string "". The resulting string "1000000.50" is then passed to the float() function for conversion.
Let’s take a look at another example:

string_with_commas = "3,141,592.65"
float_num = float(string_with_commas.replace(",", ""))
print(float_num) 
You can also try this code with Online Python Compiler
Run Code


Output: 

3141592.65


In this case, we directly pass the result of string_with_commas.replace(",", "") to the float() function, which removes the commas & converts the string to a float in a single line.

Note: It's important to keep in mind that this approach assumes the commas are used as thousand separators & the string follows a valid number format. If the string contains commas used for other purposes or has an invalid format, you may need additional processing or error handling.

Converting to a float list

In some cases, you may have a string that contains multiple numbers separated by spaces or other delimiters. To convert such a string to a list of floats, you can use a combination of string splitting and list comprehension. For example:

string_nums = "3.14 2.71 1.41 9.81"
float_list = [float(num) for num in string_nums.split()]
print(float_list) 
You can also try this code with Online Python Compiler
Run Code


Output: 

[3.14, 2.71, 1.41, 9.81]


In this example, we have a string "3.14 2.71 1.41 9.81" that contains multiple numbers separated by spaces. We use the split() method without any arguments to split the string into a list of substrings based on whitespace. This gives us a list of strings: ["3.14", "2.71", "1.41", "9.81"].

Next, we use a list comprehension [float(num) for num in string_nums.split()] to iterate over each substring num in the split list and convert it to a float using the float() function. The resulting list of floats is assigned to the float_list variable.

You can also use a different delimiter to split the string. For example:

string_nums = "3.14,2.71,1.41,9.81"
float_list = [float(num) for num in string_nums.split(",")]
print(float_list) 
You can also try this code with Online Python Compiler
Run Code


Output: 

[3.14, 2.71, 1.41, 9.81]


In this case, the string "3.14,2.71,1.41,9.81" uses commas as the delimiter. We pass "," as an argument to the split() method to split the string based on commas, and then convert each substring to a float using list comprehension.

Converting a list of strings to float

If you have a list of strings where each string represents a number, you can convert the entire list to a list of floats using the map() function. For example:

string_list = ["3.14", "2.71", "1.41", "9.81"]
float_list = list(map(float, string_list))
print(float_list) 
You can also try this code with Online Python Compiler
Run Code


Output: 

[3.14, 2.71, 1.41, 9.81]


In this example, we have a list of strings string_list where each string represents a floating-point number. We use the map() function to apply the float() function to each element of the string_list. The map() function returns a map object, which we convert to a list using the list() function. The resulting list of floats is assigned to the float_list variable.

Let’s discuss another example that combines splitting a string and converting to floats:

string_nums = "3.14 2.71 1.41 9.81"
float_list = list(map(float, string_nums.split()))
print(float_list) 
You can also try this code with Online Python Compiler
Run Code


Output: 

[3.14, 2.71, 1.41, 9.81]


In this case, we have a string string_nums containing numbers separated by spaces. We split the string using the split() method and then use map() to convert each resulting substring to a float. Finally, we convert the map object to a list using list().

Note: map() is a concise and efficient way to convert a list of strings to a list of floats. It applies the float() function to each element of the list without the need for an explicit loop.

Python Program to Parse a String to a Float Using float()

Let’s look at a complete program where a user inputs a string, and we convert it into a float.

# Python program to convert string to float
user_input = input("Enter a numerical value: ")
try:
    converted_float = float(user_input)
    print("Converted float value is:", converted_float)
except ValueError:
    print("Invalid input! Please enter a valid numerical value.")
You can also try this code with Online Python Compiler
Run Code


Output 1 (Valid Input):

Enter a numerical value: 45.67  
Converted float value is: 45.67  


Output 2 (Invalid Input):

Enter a numerical value: hello  
Invalid input! Please enter a valid numerical value.  


Explanation

  • The input() function takes user input as a string.
     
  • The try block attempts to convert the string to a float.
     
  • If the conversion fails, the except block catches the ValueError and prints an error message.

ValueError Exception

When converting a string to a float using float(), Python throws a ValueError if the string contains non-numeric characters.

Example: Handling ValueError

# Example demonstrating ValueError exception
invalid_str = "123abc"
try:
    result = float(invalid_str)
    print("Conversion successful:", result)
except ValueError:
    print("Error: The string contains non-numeric characters!")
You can also try this code with Online Python Compiler
Run Code


Output:

Error: The string contains non-numeric characters!

Key Points

  • Ensure the string contains valid numeric characters (e.g., digits, decimal points).
     
  • Use exception handling (try-except) to catch and handle errors gracefully.

Convert String to Float with Specified Decimal Points

Sometimes, you might need to round off the float value to a specific number of decimal points after conversion. Python’s round() function can help.

Example: Specifying Decimal Points

# Convert string to float with specified decimal points
num_str = "123.456789"
num_float = float(num_str)
rounded_float = round(num_float, 2)
print("Original float:", num_float)
print("Rounded float (2 decimal points):", rounded_float)
You can also try this code with Online Python Compiler
Run Code


Output:

Original float: 123.456789  
Rounded float (2 decimal points): 123.46  


Explanation

  • round() takes two arguments: the number to be rounded and the number of decimal places.
     
  • This approach is helpful when formatting data for presentation or calculations.

Convert String to Float Using NumPy

For large-scale numerical operations, NumPy provides an efficient way to convert strings to float values.

Example: Using NumPy for Conversion

# Importing NumPy
import numpy as np

# String to float using NumPy
num_str_array = ["3.14", "2.71", "0.0", "42.0"]
float_array = np.array(num_str_array, dtype=float)
print("String array:", num_str_array)
print("Float array:", float_array)
You can also try this code with Online Python Compiler
Run Code


Output:

String array: ['3.14', '2.71', '0.0', '42.0']  
Float array: [ 3.14  2.71  0.    42.  ]


Explanation

  • NumPy's array() method can convert a list of numeric strings into an array of floats using the dtype=float parameter.
     
  • This method is ideal for processing large datasets efficiently.

Using the str() function

Python provides a built-in function called float() that allows us to convert a string to a float. Let’s see how you can use it:

string_num = "3.14" 
float_num = float(string_num)
print(float_num)
You can also try this code with Online Python Compiler
Run Code


Output: 

3.14


In this example, we have a string "3.14" assigned to the variable string_num. We pass this string to the float() function, which converts it to a floating-point number. The result is then stored in the float_num variable.

The float() function can handle strings that represent both integer and decimal numbers. For example:

string_integer = "10"
float_integer = float(string_integer)
print(float_integer) 
You can also try this code with Online Python Compiler
Run Code


Output: 

10.0


Even though the string "10" represents an integer, the float() function still converts it to a float, resulting in 10.0.

It's important to note that the string must contain a valid number for the conversion to work. If the string contains non-numeric characters (except for a leading sign or decimal point), the float() function will raise a ValueError. For instance:

invalid_string = "3.14abc"
float_invalid = float(invalid_string)  # Raises ValueError
You can also try this code with Online Python Compiler
Run Code


In this case, the string "3.14abc" contains non-numeric characters, so attempting to convert it to a float will result in an error.

Frequently Asked Questions

What happens if the string contains invalid characters during conversion?

Python raises a ValueError if the string contains non-numeric characters. Use exception handling (try-except) to manage such cases.

Can I convert a list of strings to floats without a loop?

Yes, you can use NumPy's array() function with dtype=float to convert a list of numeric strings into a float array efficiently.

How do I round a float to two decimal points after conversion?

Use Python’s round() function. For example, round(float("123.456"), 2) results in 123.46.

Conclusion

In this article, we discussed how to convert strings to floats in Python using various methods, including the float() function, handling exceptions, and using NumPy for bulk operations. Understanding these techniques is essential for tasks like data preprocessing, numerical computations, and file handling.

Recommended Readings:

Live masterclass