Convert string to float in python

In this article, we will discuss how to convert a number string to a float object.


Table of Contents

Python provides a function to convert a number string into a floating-point number.

Syntax of float() function

float(object)

Parameters

  • It can be an int, float, or string.
  • If it is a string, then it must be of correct decimal format.

Returns

  • It returns a float object.
    • If the provided string contains anything other than a floating-point representation of a number, then it will raise ValueError
    • If no argument is provided, then it returns 0.0
    • If the given argument is outside the range of float, it raises overflow Error.

Let’s see some examples, where we will use the float() function to convert string to a float object.

Convert string to float object in python in python

Suppose we have a string ‘181.23’ as a Str object. To convert this to a floating-point number, i.e., float object, we will pass the string to the float() function. Which converts this string to a float and returns the float object. For example,

value = '181.23'

# Convert string to float
num = float(value)

print(num)
print('Type of the object:')
print(type(num))

Output:

181.23
Type of the object:
<class 'float'>

Convert number string with commas to float object

Suppose we have a string ‘10,181.23’, it contains the number but also has some extra commas. To convert this kind of string to float is a little tricky. If we directly pass this to the float() function, then it will raise an error. For example,

value = '10,181.23'

num = float(value)

Output:

ValueError: could not convert string to float: '10,181.23'

As string had characters other than digits, so float() raised an error. So, we need to remove all the extra commas from the string before passing it to the float() function. For example,

value = '10,181.23'

# convert string with comma to float
num = float(value.replace(',', ''))

print(num)
print(type(num))

Output:

10181.23
<class 'float'>

Summary

We can convert a number in a string object to a float object using the float() function.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top