Python Convert String to Float

How to convert a String to Float in Python? Converting a string to a float is a common operation, especially when working with numerical data stored in text files or received as input. In this article, we will look at various techniques for converting a string to a float in Python. The simple method is using the float() function, which is not always the solution. So let’s discuss it in detail.

Quick Examples of Converting String to float

If you are in a hurry, below quick examples will help you in understanding the different ways to convert a string to a float in Python. We will discuss them in detail with other important tips.


# Quick Examples

# Method 1: Convert string to float using float() 
string_to_float = float("123.45")  

# Method 2: Convert string to float using the decimal module
import decimal
string_with_comma = "1,234.567"
decimal_float = decimal.Decimal(string_with_comma.replace(',',''))  

# Method 3: Using regular expression 
import re
pattern = r'^-?\d+\.\d+$'
float_string = "123.45"
match = re.match(pattern, float_string)
if match:
    regex_float = float(float_string)  
else:
    print("Not a valid float string")
    

# Method 4: Use the float.fromhex() 
hex_string = "0x3.a7p10"
hex_float = float.fromhex(hex_string)  

# Method 5: Use the try and except statements 
invalid_string = "not a float"
try:
    invalid_float = float(invalid_string)
except ValueError:
    print("Could not convert string to float")

1. The Difference between String and Float in Python

In Python String and float are two different types of datatypes. Here are three points that can show the differences between strings and floats in Python:

  • Type: A string is a sequence of characters, represented as a str object in Python. A float is a numerical value with a decimal point, represented as a float object in Python.
  • Representation: A string is represented by enclosing a sequence of characters in single or double quotes, like this: 'Hello, World!' or "3.14159". A float is represented by a numerical value with a decimal point, like this: 3.14159.
  • Usage: Strings are typically used to represent text data, such as names, addresses, or messages. Floats are typically used to represent numerical data, such as measurements or calculations.

# Declaring strings
string1 = 'Hello, World!'
string2 = "3.14159"

# Declaring floats
float1 = 3.14159
float2 = -0.5

# Printing the type of each variable
print(type(string1))  # Output: class 'str'
print(type(string2))  # Output: class 'str'
print(type(float1))   # Output: class 'float'
print(type(float2))   # Output: class 'float'

2. Convert String to Float using float() Function

The float() function is a built-in function in Python that converts a string or a number to a float type. It is a simple and widely used method for converting a string or a number to a float.

The float() function is flexible and can handle a variety of string formats. As long as they contain a valid float representation. For example, you can use the float() function to convert strings with leading or trailing spaces. It can also convert strings that contain a leading or trailing plus or minus sign.


# Convert String to Float
string1 = " 3.14159 "
float_value1 = float(string1)
print(float_value1)
  
# Output: 
# 3.14159

# Convert String to Float with + sign
string2 = "+10.5"
float_value2 = float(string2)
print(float_value2)  

# Output: 
# 10.5

# Convert String to Float with - sign
string3 = "-0.1"
float_value3 = float(string3)
print(float_value3) 
 
# Output: 
#-0.1

3. Convert String Representing Binary to Float

The float() function is of course more powerful but it can only convert strings to floats in base 10. So if you want to binary float representing in string format. You need to use another approach.

These are the steps that you can follow to Convert string representing binary decimal values to float.

  1. Split the string into the integer part and the fractional part using the split() method.
  2. Use the int() function to convert the integer part of the binary string to an integer in base 2.
  3. Iterate over the fractional part of the string and convert each binary digit to a float.

# Convert binary string to integer
string = "1011.1"
integer = int(string.split(".")[0], 2)
print(integer)  

# Output: 
# 11

# Convert fractional part of binary string to float
fraction = 0.0
for i, c in enumerate(string.split(".")[1]):
    fraction += int(c) / (2 ** (i + 1))
print(fraction)  

# Output: 
# 0.5

# Combine integer and fractional parts to get float value
float_value = integer + fraction
print(float_value)
  
# Output: 
# 11.5

4. Convert String Non Base 10 Values to Float

Just like in the above example, we can convert any string representing any base to float. We can follow the same formula we applied to the binary values in the above example.

Check the following example we have converted a string that represented a base 16 value to float.


def parse_float(string, base):
    """Convert a string to a float in the specified base"""
    # Initialize float value and sign
    value = 0.0
    sign = 1
    # Check for negative or positive sign
    if string[0] == "-":
        sign = -1
        string = string[1:]
    elif string[0] == "+":
        string = string[1:]
    # Split string into integer and fractional parts
    parts = string.split(".")
    integer_part = parts[0]
    fraction_part = parts[1] if len(parts) > 1 else ""
    # Convert integer part to float
    for i, c in enumerate(integer_part):
        value = value * base + int(c, base)
    # Convert fractional part to float
    fraction = 0.0
    for i, c in enumerate(fraction_part):
        fraction += int(c, base) / (base ** (i + 1))
    # Add integer and fractional parts
    value += fraction
    # Return value with correct sign
    return value * sign

# Convert string to base 16 float
string = "FF.7"
base = 16
float_value = parse_float(string, base)
print(float_value)  

# Output:
# 255.4375

5. Convert String to Float using Decimal Module

The decimal module in Python can be useful if you need to perform precise calculations with decimal values. It supports arbitrary-precision decimal arithmetic. It can avoid the round-off errors that can occur when using the built-in float type.


import decimal

# Convert string to decimal value with specified precision
string = "123.456789"
precision = 3
decimal_value = decimal.Decimal(string)

# Set precision of decimal value
decimal_value = decimal_value.quantize(decimal.Decimal(f"0.{'0' * precision}"))

# Convert decimal value to float
float_value = float(decimal_value)
print(float_value)  

# Output: 
# 123.457

6. Using Regular Expression to Convert String to Float

A regular expression is used to find and extract specific patterns of characters from a string. We can use a regular expression to match and extract the float value from a string in Python. We can use the re module and the search() function to find a float value in the string. Once we find the float value we can use the float() function to do the conversion.


import re

# Convert string to float using regular expression
string = "String-123.45678."
# Regular expression pattern to match float value
float_pattern = r"[+-]?\d*\.\d+"  
float_match = re.search(float_pattern, string)
float_value = float(float_match.group())
print(float_value) 
 
# Output: 
# -123.45678

7. Use float.fromhex() to Convert Hexadecimal Format to a Float

In previous examples, we have seen how the conversion from string to float that are not in base 10. Yet we have another function that can help us do the conversion on base 16.

To use the float.fromhex() method, you simply pass the string in hexadecimal format as an argument. This method is useful for converting hexadecimal floating-point literals.


# Convert hexadecimal string to float
hex_string = "0a.921f"
float_value = float.fromhex(hex_string)
print(float_value)  

# Output: 
# 10.570785522460938

8. Handle Exceptions when Converting String to Float

The built-in float() function can raise a ValueError exception if it is passed a string that cannot be converted to a float. We can enclose the conversion code in a try block and use an except block to catch the ValueError exception.


# Convert string to float, handling exceptions
string = "351.159"
try:
    float_value = float(string)
except ValueError:
    print("Could not convert string to float")
    float_value = 0.0

print(float_value) 
 
# Output: 
# 351.159

9. Tips to Convert String to Float in Python

There are several ways to do this conversion, and it is important to choose the method that best meets your needs. We have discussed a few of them. Here are a few points that you should keep in mind while doing the conversion from string to float.

  1. The built-in float() function is the easiest and most straightforward way to convert a string to a float in Python.
  2. If you need to perform precise decimal calculations, use the decimal module to convert a string to a float.
  3. Use a regular expression to extract a float value from a string.
  4. Use the float.fromhex() method to convert a hexadecimal string to a float.
  5. Use the try and except statements to handle exceptions

Summary and Conclusion

You should now have everything you need to effectively convert string to float in your Python programs. If you have any questions, please don’t hesitate to leave a comment. I would be happy to help!

AlixaProDev

I am a software Engineer with extensive 4+ years of experience in Programming related content Creation.

Leave a Reply