You are currently viewing How to Convert String to Float in Python

How to Convert String to Float in Python

In Python programming, you will frequently run into situations in which data must be converted from one type to another. For instance, you might have a string that contains a number, and you need to convert it to a float to do the math on it. You can use python type casting function float() to convert string to float in python.

Example 1:

str = '3942.54'
flt = float(str)

print("Type of orignal string: " , type(str))
print("Type of converted string: ", type(flt))

Output:

Type of orignal string:  <class 'str'>
Type of converted string:  <class 'float'>

Example 2:

str_1 = '345.23'
str_2 = '453.67'

# Type Casting

flt_1 = float(str_1)
flt_2 = float(str_2)

# Addition of Numbers

add_str = flt_1 + flt_2
print("Addition of Numbers: ", add_str)

Output:

Addition of Numbers:  798.9000000000001

References:

https://docs.python.org/3/

Leave a Reply