Skip to content
Home » How to Convert String to Float in Python

How to Convert String to Float in Python

In this tutorial let’s learn about How to Convert String to Float in Python. Python has type conversion functions that allow you to directly convert one data type to another. The purpose of this article is to provide information on converting a string to a float. To convert a String to a float in Python, use float().

Convert String to Float using float() Method in Python

Any data type can be converted to a floating-point number using this float() function.

Syntax for float()

float(var)

var : it can be string or int datatype.

Code Example :

string= "12.3"

# converting string to float
value = float(string)

print(value)
print(type(value))

Output :

12.3
<class ‘float’>

Other example:

x = float("34.567")
# output: 34.567

y = float("2")
# output: 2.0

z = float(5)
# output: 5.0

As you can see, the strings above have been turned into a floating object. The only thing to remember is that the string must have a numerical decimal or integer value; otherwise, the float function will not be able to convert the string to float.

You can use the type() function before and after using the float to check the data kinds. This function returns the object’s data type. Values of various data types, like float() can be converted to integers and strings using the int() and str() functions.

Conclusion

in this tutorial we learnt about how float() method is used to convert the strings into floating point values in python.

Similar Posts:

How to Convert Bytes to String in Python
How to Convert a List to String in Python