1

I am trying to parse a string which contains a number and when I try to convert it to a float, it gives me an error:

ValueError: could not convert string to float: '8,900'

My code:

soup=BeautifulSoup(content,"html.parser")
element=soup.find("div",{"class":"_1vC4OE _3qQ9m1"})
price=element.text
price_without_symbol=price[1:]
print(float(price_without_symbol));

Output:

"C:\Users\SHIVAM TYAGI\PycharmProjects\price-of- chair1\venv\Scripts\python.exe" "C:/Users/SHIVAM TYAGI/PycharmProjects/price-of-chair1/src/app.py" Traceback (most recent call last): File "C:/Users/SHIVAM TYAGI/PycharmProjects/price-of-chair1/src/app.py", line 9, in print(float(price_without_symbol)); ValueError: could not convert string to float: '8,900'

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

3

Depending on the numeric convention used, a comma can either denote a thousands separator or a decimal point.

Python float numbers syntax uses a dot (.) as decimal point and an optional underscore (_) as thousand separator, for readability only.

This means you need to know which numerical convention the number you are reading uses.

In your case it would seem you are reading numbers using the US-English numeric convention.

US-English | 4,294,967,295.00

All you need is to remove the comma which acts as thousands separator.

price_without_symbol=price[1:].replace(',', '')
print(float(price_without_symbol))
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73