Saturday, December 28, 2024
Google search engine
HomeLanguagesConvert String to Float & Float to String in Python

Convert String to Float & Float to String in Python

Convert string to float and float to string in python; In this tutorial, you will learn two simple methods to convert string to float and convert float to string in python.

You can use the built-in float method to convert the string into float number in python. And You can use the built-in string str() function of Python to convert float numbers to string in python.

How to convert string to float and float to string in python

  • The python float() is a standard built-in function to convert the string into a float value.
  • The python str() is a standard built-in function to convert the integer, float number to a string value.

Python Convert String to float

You can convert a string to float in Python using a python built-in float() method. Internally float() function calls specified object __float__() function.

Let’s look at a simple example to convert a string to float in Python.

s = '10.5674'

f = float(s)

print(type(f))
print('Float Value =', f)

Output:

<class 'float'>
Float Value = 10.5674

Python program to convert a string to float:

If you have a string in python and you want to convert it to float number. So you can use python built-in function float() to convert string to floating number in python.

Python program to convert string to float:

num = "3.1415"

print(num)
print(type(num))  # str

pi = float(num)  # convert str to float

print(pi)
print(type(pi))  # float

Output

3.1415
<class 'str'>
3.1415
<class 'float'>

Python Convert float to String

You can convert float to a string easily using the pyhon built-in str() method. This might be required sometimes where we want to concatenate float values.

python program converts float to string:

pi = 3.1415

print(type(pi))  # float

piInString = str(pi)  # float -> str

print(type(piInString))  # str

Output:

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

Recommended Python Tutorials

RELATED ARTICLES

Most Popular

Recent Comments