Kodeclik Blog

How to convert a string to a float in Python

Recap that strings are used to denote names, addresses, etc and floats are used to represent real numbers, Sometimes you might have input a value from a user which was intended to be a floating point variable but instead got stored as a string. You will need to convert it into a float inside your Python program. Let us learn how to do this!
First, let us create a program to obtain a floating point value from the user:
If we run this program, here is a sample interaction:
Note that the user’s input (which was “75”) is internally stored as a string so that when we print the type of the input, we obtain ‘str’ as the answer. This means we cannot do any arithmetic operations on it, like addition, subtraction, etc. We will need to convert it into a floating point value.
The way to convert a string to a float is to use the float() function, like so:
If we run the above program:
Note that the variable which was a string before is now a float, and reflects it in its value as 75.0.
This also means that we can input floating point values when queried:
Here, the 75.345 which used to be a string is converted to a float with the above value.
On the other hand, if we do:
We cannot map “hot” to a float using the float() function. The input to float() must be a string containing only numbers (and perhaps decimal points and negative signs).
As we have seen in this blogpost, it is extremely easy to convert a string to a float so that you can do arithmetic operations on the result which you could not do before.
For more Python content, checkout the math.ceil() and math.floor() functions! Also learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.