In this article, we will discuss how to convert a number string to a float object.
Table of Contents
- Syntax of float() function
- Convert string to float object
- Convert number string with commas to float object
Python provides a function to convert a number string into a floating-point number.
Syntax of float() function
- It can be an int, float, or string.
- If it is a string, then it must be of correct decimal format.
- 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))
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)
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))
10181.23 <class 'float'>
We can convert a number in a string object to a float object using the float() function.
Pandas Tutorials -Learn Data Analysis with Python
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.