What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

6 Ways to Convert String to Float in Python

  • Aug 31, 2021
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Shivali Bhadaniya
6 Ways to Convert String to Float in Python

When you take a user input in python programming while working with terminal or file operations like reading or writing a file, the input is a string object. Even though you ask for the floating-point value, the input method in python will fetch the user input as a string object. Hence, you have to explicitly convert the string into a floating-point value so that you can perform the necessary operations on it. Before understanding the methods to convert the string to float explicitly, let us first go through the strings and float data types in python.

What are strings in python?

A string is a series of characters inside the quotes. You can use single quotes or double quotes to display the string. Also, triple quotes are used to display the multi-line quotes.

As you know, that computer does not deal with characters but instead, it works only with binary numbers. Therefore, the characters you input in the system are converted into a binary format using the encoding techniques like Unicode and ASCII. In python, the string is a sequence of Unicode characters which include every character and symbol in all languages. Square brackets are used to access the string elements along with the index position of the string character. The indexing of character in a string starts from ‘0’, and therefore, the string's first character always has the index equal to zero.

For Example

# defining strings in Python
s = 'Favtutor'
print(s)

s = "Favtutor"
print(s)

s = '''Favtutor'''
print(s)

# multi-line string
s = """Compile with
    Favtutor"""
print(s)

 

Output

Favtutor
Favtutor
Favtutor
Compile with
    Favtutor

 

What is Float in python?

Float is one of the data types of python programming that is used to represent the floating-point number. Float is always written with the decimal points by dividing the integer and fractional parts. IEEE 754 standard represents the float as 64-bit double-precision values. Therefore you can say that the floating-point numbers are represented internally as binary(base-2) fractions. The maximum value of any floating-point number can be approximately 1.8 x 10308. If any number is greater than this, you can indicate them by the string ‘inf’ in Python

For Example

a = 3.14
print(type(a))
print(a)

 

Output

<class 'float'>
3.14

  

Convert String to Float in Python

Below are 6 common and simple methods used to convert a string to float in python

1) Using float() function

You can use the float() function to convert any data type into a floating-point number. This method only accepts one parameter. If you do not pass any argument, then the method returns 0.0. If the input string contains an argument outside the range of floating-point value, OverflowError will be generated.

For Example

s = '10.123'
f = float(s)
print('Float Value =', f)

 

Output

Float Value = 10.123

 

If the input string contains anything other than a floating-point representation of a number, the output will be ValueError. Let us understand this in detail below.

2) Convert a Number String with commas into a floating-point object

Consider that the input string is ’1,0.123'. As you can see, the string contains numbers, but it also has a comma in it. Therefore, converting this kind of string into a floating-point value is very tricky. If you directly call the float() method, then the output will raise an error.

For Example

s = '1,0.123'
f = float(s)
print('Float Value =', f)

 

Output

ValueError: could not convert string to float: '1,0.123'

You have to remove all the commas from the string before calling the float() function to solve this issue. Take a look at the example below to understand better.

For Example

s = '1,0.123'
f = float(s.replace(',',''))
print('Float Value =', f)

 

Output

Float Value = 10.123

 

3) Convert string to float list in python

In this method, firstly, you need to initialize the string, and later, you can use the float() and split() method to convert a string into the floating-point list, as shown below in the example.

For Example

s = "2.41, 6.81, 3.9, 10.21, 62.0"
res = [float(value) for value in s.split(', ')]
print("The float list is : " + str(res))

 

Output

The float list is : [2.41, 6.81, 3.9, 10.21, 62.0]

 

4) Convert a list of strings to float in python

The list of strings is the python list containing all elements as strings in it. To convert this list of strings into floating-point values, you have to use for loop to iterate through each item of the list. Later, you can use the float() method to convert each item into float value and then append it to the list again. Check out the below example for reference:

For Example

s = ['11.11', '22.22', '33.33', '33.44']
f = []
for item in s:
    f.append(float(item))
print(f)

 

Output

[11.11, 22.22, 33.33, 33.44]

 

5) Convert String to Float using Numpy

Numpy is one of the libraries for python programming, which supports large, multi-dimensional arrays and matrices to perform high-level mathematical operations. If you want to convert a string into float using NumPy, the first step will be to import the NumPy library using “import NumPy as np.” Later, you can use the “astype” method, an in-build method used to convert the string to a floating-point value in python.

For Example

import numpy as np
s = np.array(["1.267", "1.456", "0.012"])
f = s.astype(float)
print(f)

 

Output

[1.267 1.456 0.012]

 

6) Convert String to Float with Specified Decimal Points

It is often necessary to bring the precision for the number of zeros after the decimal in floating-point values. In such cases, you can use the float() method to convert a string into float value and then use the format() method to specify the number of decimal points in the float value. The syntax of the format method is as given below:

“{:.Nf}”.format(float value)

Here, N displays the number of decimal points you wish to put. If the floating-point value generated has fewer decimal points than the suggested, then zeros are added at the end to round it. Take a look at the example below for a better understanding.

Example

s = "3.14159"
f = float(s)
result = "{:.3f}".format(f)
print(result)

 

Output

3.142

 

Conclusion 

While programming, there are many situations where you have to convert one data type into another to perform the necessary operations. This article refers to the python string and float values in detail and the explicit methods used to convert strings into floating-point values. As the input method in python accepts the string object for user input, it is necessary to learn and understand these methods to convert the string into float data type to perform different operations on user data.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Shivali Bhadaniya
I'm Shivali Bhadaniya, a computer engineer student and technical content writer, very enthusiastic to learn and explore new technologies and looking towards great opportunities. It is amazing for me to share my knowledge through my content to help curious minds.