Skip to Content

Convert String to Float in Python

In this tutorial, we will look at how to convert a string in Python to a float value, that is, float datatype with the help of some examples.

How to convert string to float in Python?

convert string to float in python

You can use the Python built-in float() function to convert a string to a float value in Python. The following is the syntax –

# convert string s to float
float(s)

It returns the passed string as a floating-point value. Note that if the passed string does not represent a numeric value, it will raise an error.

Examples

Let’s look at some examples of using the above syntax to convert a string to a floating-point value.

First, let’s apply the float() function on a string containing a real number with a decimal part, for example, “150.75”.

# string storing a float number
s = "150.75"
# convert string to float
num = float(s)
# display the number and its type
print(num)
print(type(num))

Output:

150.75
<class 'float'>

You can see that we get 150.75 as a float value.

What happens if you pass an integer number as a string to the float() function? Let’s find out.

# string storing an integer
s = "150"
# convert string to float
num = float(s)
# display integer and its type
print(num)
print(type(num))

Output:

150.0
<class 'float'>

We get 150.0 as a float point number after conversion.

If you want to convert the above string to an integer in Python, use the int() function instead.

# string storing an integer
s = "150"
# convert string to int
num = int(s)
# display number and its type
print(num)
print(type(num))

Output:

150
<class 'int'>

We get the string as an integer.

What happens if you pass a non-numeric string to the float() function? Let’s find out.

# string with text
s = "cat"
# convert string to float
num = float(s)
# display number and its type
print(num)
print(type(num))

Output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [4], in <module>
      2 s = "cat"
      3 # convert string to float
----> 4 num = float(s)
      5 # display number and its type
      6 print(num)

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

As expected, we get an error because the passed string cannot be represented as a floating-point number.

You might also be interested in –

  1. Extract Numbers From String in Python
  2. Python – Check if String Contains Only Numbers
  3. Python Tuple to Integer


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush

    Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.