Python – How to convert String to float

In Python, we can use float() 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'>

References

  1. Python docs – float()
author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
3000
newest oldest most voted
Arpita Das
Guest
Arpita Das

Please help me out to resolve below error

If I write like this

n = input(“Enter a numerical expression: “)
print(float(n))

got below error

print(float(n))
ValueError: could not convert string to float: ‘5.5+6.5’

Expected Output: 12

avalon leo
Guest
avalon leo

def priceOf(stockSymbol):
html = _readHTML(stockSymbol)
trade = html.find(‘yfs_l84’, 0)
beg = html.find(‘>’, trade)
end = html.find(‘‘, beg)
price = html[beg + 1: end]
price = price.replace(‘,’, ”)
return (float(str(price)))
This piece of could not convert string to float….The very last line…can you help in converting this string to a float…please..