Javaexercise.com

How to Convert Float to String in Python?

To convert float to string type, we will use Python str() function. Python provides a str() function which is used to create a string object. If argument is not provided, it returns an empty string. We can use this fuction to perform conversion between float to string type.

Let's see an example to understand the conversion of float to string type in Python.

Example: Float To String Converesion

Here, we have a variable 'a' that stores a float value and then converted to string by using the str() function. We are using type() function as well to check variable type. See the example here.

# Take an float value
a = 10.50
print(a)
# Display type of value
print(type(a))
# Convert float to string
a = str(a)
# display type and value
print(a)
print(type(a))

Output:

10
<class 'float'>
10
<class 'str'>

 

Python String to Float Conversion

In the above example, we saw conversion of float to string type. Now, let's see the conversion from string to float type. To convert a string to float, we will use Python float() function that will returns a float object. See the example here.

Example: Convesion String to Float

Here, we have a variable 'a' that stores a string value and we are converting it to float by using the float() function. See, the result type is float that shows the successfull conversion of values.

# Take a string value
a = "10.50"
print(a)
# Display type of value
print(type(a))
# Convert string to float
a = float(a)
# display type and value
print(a)
print(type(a))

Output:

10
<class 'str'>
10
<class 'float'>

 


Conclusion

Well, in this topic, we learnt to convert float to string and vice versa. We used str() and float() functions to convert float to string and string to float respectively.

If we missed something, you can suggest us at - info.javaexercise@gmail.com