Python String to Float – Definitive Guide

Python Strings are a sequence of characters. It is either surrounded by single quotation marks or double quotation marks. When you get input from the user or read a column from the files, even the numbers are parsed as Strings. In that case, you need to convert String to Float to perform various arithmetic operations on it.

In python, you can convert string to float using the float() method.

In this tutorial, you’ll learn how to convert python string to float using the float() method along with the exceptions to be handled and the number of decimal points to be retained.

If You’re in Hurry…

You can use the below code snippet to convert String to Float by using the float() method.

str = '77.8579'

f = float(str)

f

Output

77.8579

To know more about the exceptions and the decimal points, read the tutorial.

If You Want to Understand Details, Read on…

In this tutorial, you’ll learn the different methods available to convert String to Float along with the decimal points, comma separator, scientific notation, converting a binary String or a byte String to float.

Python String to Float

You can convert String to float using the float() method.

To know the type of the variable in Python, you can use the type() method.

The below example type(str) displays the type of the st variable. Its class 'str' which means it’s a String variable.

Next, you’ll convert the st variable to float by using the float(st) method and the value is stored in the variable f. When you print the type of f, its class float which means it’s a float variable.

Then while printing the value of the variable f, it’s just printed without any quotation marks. It shows it’s just a number.

st = '77.8579'

print("Type of variable S :" , type(st))

f = float(st)

print("\nType of variable f :" , type(f))

print("\nValule of float variable f =", f)

Output

Type of variable S : <class 'str'>

Type of variable f : <class 'float'>

Valule of float variable f = 77.8579

This is how you can know the type of the variable and convert the String to float.

Next, you’ll see the exception to be handled while using the float() method.

Exception

When using the float() method, it’ll throw the below exceptions.

  • ValueError – When an invalid number is passed or if the String contains any invalid characters like ,.
  • OverflowError – If the String is outside the range of Python Float. Minimum Float value is 2.2250738585072014e-308 and maximum float value is 1.7976931348623157e+308. Check this link for more details about the floating point limits.

Example

Below is the example to convert the String with characters other than the value numbers. When you pass this invalid number to float(), you’ll see the ValueError as shown below.

s = 'test'

f = float(s)

print("\nType of variable f :" , type(f))

print("\nValue of float variable f =", f)

Output

    ---------------------------------------------------------------------------

    ValueError                                Traceback (most recent call last)

    <ipython-input-3-2d3c128dacdd> in <module>
          1 s = 'testt'
          2 
    ----> 3 f = float(s)
          4 
          5 print("\nType of variable f :" , type(f))


    ValueError: could not convert string to float: 'testt'

To avoid this error, you need to catch the ValueError exception is shown in the next section.

Convert String to Float Exception

You need to enclose the float() method in try block. Then if there is an exception while converting a String to float, then the exception will be thrown.

In the except block, you can catch the ValueError and specify what needs to be done in case of Exception.

In the below example, you’ll catch the ValueError exception and printing a proper message to the user.

Snippet

s = "77,888.805"

try:
    s_as_float = float(s)

except ValueError:

    print("Invalid Float number to be converted. ")

Output

Invalid Float number to be converted. 


This is how you can convert String to float with Exception handling.

Convert String to Float with 2 Decimal Points

In this section, you’ll convert String to Float with 2 decimal points.

Even if the String variable has more than two decimal points, you’ll convert it to float first using the float() method and then format the float number to have only 2 decimal points using the format() method.

For example, "{:.2f}".format(s_as_float) is used to format float with 2 decimal points. .2f denotes how many decimal points needs to be available in the float number. You can use .5f if you want to have 5 decimal points.

Snippet

s = "3.14159"

s_as_float = float(s)

formatted_float = "{:.2f}".format(s_as_float)

formatted_float

Since you’ve used the .2f, you’ll see the output float number will have two decimal points as shown below.

Output

'3.14'

This is how you can handle decimal points in the floating-point numbers.

Convert String With Comma to Float

You can convert a string number with a comma to float by replacing all the commas in the String.

By default, the float() method doesn’t handle String with Comma. Hence you need to replace the comma with an empty String and then pass it to the float() method as shown below.

Snippet

s = "77,888.805"

s_as_float = float(s.replace(',',''))

s_as_float

All the commas will be replaced to String and the resultant number will be converted to float as shown below.

Output

 77888.805

This is how you can convert String with a comma to a float number.

Convert String to Float With Default Value

In this section, you’ll learn how to convert String to float with the default value.
This means, when a String to float conversion fails, a default number should be returned to you.

Python doesn’t implicitly support a method to return a default value when the conversion fails. Hence, you’ll need to create a custom function to return a default value.

In the below example, it’ll return the default float value by using the float() method.

def convert_float(s):
    try:
        f = float(s)
    except ValueError:
        f = float()
    return f

s = "3,141.59"

s_as_float = convert_float(s)

s_as_float

Since the input String contains a number with a comma, float conversion will fail. Then in the exception block, a default float value 0.0 is assigned to the variable and it’ll be returned to the calling function.

You’ll see the below output.

Output

0.0

This is how you can convert String to float with the default value.

Convert String to Float NaN

In this section, you’ll learn how to convert String to Float. If the conversion is failed due to invalid values, then you’ll assign the float NaN value.

NaN means Not a Number and it is used to denote the missing data.

NaN value is available in the NumPy package. You need to import the NumPy package using the below statement.

import numpy as np

To assign NaN value to float in case of failed conversion, catch the ValueError that will be thrown when the String to Float conversion fails and assign the NaN value using np.nan as shown below.

Snippet

import numpy as np

def convert_float(s):
    try:
        f = float(s)
    except ValueError:
        f = np.nan
    return f

s = "3,141.59"

s_as_float = convert_float(s)

s_as_float

Since the String has the character , in it, then float conversion will be failed and the during the exception catch, Np.nan value will be assigned as returned.

You’ll see the below output.

Output

nan

This is how you can convert String to float Nan in case of invalid float numbers.

Convert String to Float Keep Precision

To convert String to float and keep precision as such, you can just use the float() method. It’ll convert the String object to a number and then display it as a float with the same precision.

s = "3.14159"

s_as_float = float(s)

s_as_float

Output

3.14159

With Trailing Zeros

To preserve trailing zeros or add a required number of trailing zeros, you can use the format function. It’ll add the necessary number of zeros to make the number of the preferred length.

Snippet

print('{0:.10f}'.format(1.6))

Output

1.6000000000

Convert Scientific Notation String to Float

Scientific notation Strings are strings with a very large number or very small number which are conveniently written in the normal decimal form.

You can convert these types of notations to float numbers by using the float() constructor. It accepts the notation and converts it to the normal float number.

Snippet

f = float('1.31E+01')

f

The notation is converted to the normal floating-point number and you’ll see the below output.

Output

13.1

This is how you can use the float() with scientific notations.

Convert Binary String to Float

Binary Strings are strings that are used to store non-traditional data such as pictures where the normal string is used to store the textual data.

To convert the binary string to float, first, you need to evaluate the binary string and identify the correct number equivalent to the binary number.

You can use the eval() method to evaluate the binary String to number.

Snippet

eval('-0b1110')

You’ll see the binary value converted to a normal number as shown below.

Output

-14

Now, you can use the same method inside the float() method to convert the String to Float.

Snippet

f = float(eval('-0b1110'))
f

The binary string will be converted to float number and you’ll see the below output as float.

Output

-14.0

This is how you can convert the binary string to float.

Convert Byte String to Float

A byte string is a sequence of bytes – that can be stored on a storage disk. To understand the difference between byte string and normal String, refer to this link.

You can convert such byte strings to float using the python struct library.

This library performs the conversion of Bytes to python values and vice versa.

To convert the byte to normal value, you need to use the struct.unpack().

unpack() method accepts two parameters.

  • format – Format type of the resultant value
  • buffer – The byte string to be unpacked.

Use the below snippet to convert byte string to float by using f in place of format parameter.

Snippet

import struct

x = struct.unpack('f', b'\xdb\[email protected]')

x

You’ll see the float equivalent of the byte string unpacked using the struct.unpack.

Output

(3.1415927410125732,)

This is how you can convert byte strings to a floating-point numbers.

Convert List of String to Float

In this section, you’ll learn how to convert a list of String to float.

There are two methods available to convert a list of String to float.

  • Using List Comprehension
  • Using Numpy Float_

Both are explained below.

Using List Comprehension

To convert the list of Strings to float, you can use the list comprehension and convert each value to float using the float() method.

List comprehension provides a way to create a new list with an operation performed on each value available in the list. Here the operation is converting the number to float().

Snippet

lst= [ '0.54', '0.54', '0.55', '0.54','0.55', '0.54', '0.55', '0.55', '0.54']

floats = [float(i) for i in lst]

floats

A new list called floats is created with the float values obtained by converting the String values available in the list. When you print the floats, you’ll see the float values.

Output

[0.54, 0.54, 0.55, 0.54, 0.55, 0.54, 0.55, 0.55, 0.54]

Using Numpy Float_

You can convert a list of Strings to float using the np.float_() method. float_ is an extended scalar array type. When you use this you’ll create an array of float values.

For using this, you need to import the numpy as np.

Then pass the list of Strings to np.float_(). It’ll return an array with floats. You can pass this array to list() method to create a list of values.

Snippet

import numpy as np

lst= [ '0.54', '0.54', '0.55', '0.54','0.55', '0.54', '0.55', '0.55', '0.54']

list(np.float_(lst))

You’ll see a list of floating numbers created out of a list of Strings.

Output

[0.54, 0.54, 0.55, 0.54, 0.55, 0.54, 0.55, 0.55, 0.54]

This is how a list of Strings can be converted to float using the list comprehension and the numpy.float_.

Conclusion

To summarize, you’ve learned how to convert String to float in Python.

Additionally, you’ve also learned how to

  • Handle errors that occur during the conversion
  • Handle the strings with comma
  • Handle scientific notation Strings
  • Binary strings and the byte strings

If you have any questions, comment below.

You May Also Like

Leave a Comment