-1

I have a problem with turning a string into a float value. I'm screaming a website and trying to get the prices in to float values, but the problem is that the prices can look like this:

$2,549.98

$2,262.64

$999.00

marketprice = driver.find_element_by_xpath('/html/body/app/content-holder/marketplace-detail/landfield-detail/div/div/div[2]/div/div[1]/div[2]/span')
userprice = driver.find_element_by_xpath('/html/body/app/content-holder/marketplace-detail/landfield-detail/div/div/div[2]/div/div[1]/div[6]/span')
print(marketprice.text, userprice.text)
imarketprice = float(marketprice.text[1:])
iuserprice = float(userprice.text[1:])

When I try to convert the error I get:

ValueError: could not convert string to float: '2,549.98'

Is the problem with it that there are a comma and a dot?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
loveruski
  • 1
  • 2
  • 1
    You could just remove the commas. FYI normally not a good idea to represent monetary amounts as floats. – khelwood Jan 14 '21 at 13:03
  • yes that is the problem – Chris Jan 14 '21 at 13:04
  • @Chris not really. Because a *lot* of text files use thousand separators. You need to use the proper parsing method, not just use `float()` – Panagiotis Kanavos Jan 14 '21 at 13:07
  • Proposing to remove thousand separators is a hack. There are **good duplicates** [like this one](https://stackoverflow.com/questions/1779288/how-to-convert-a-string-to-a-number-if-it-has-commas-in-it-as-thousands-separato) – Panagiotis Kanavos Jan 14 '21 at 13:08
  • 2
    Use `locale.atof` instead. Replacing won't work in half of the world, where `,` is the *decimal* separator. If you try replacing commas in Europe, Russia, Africa or South America you'll end up removing the decimal separator – Panagiotis Kanavos Jan 14 '21 at 13:09
  • 1
    The currently accepted answer in the duplicate is NOT the right way to do this. Use [this answer](https://stackoverflow.com/a/6633912/2386774) instead. Money should always be represented as Decimal, not float. – JeffC Jan 14 '21 at 15:32

1 Answers1

1

Just remove the commas using:

imarketprice = float(marketprice.text[1:].replace(",", ""))
The Pilot Dude
  • 2,091
  • 2
  • 6
  • 24
  • 2
    That's a hack that only works for very specific locales, esp. US and China. It won't work in half of the world. `locale.atof` can handle any locale – Panagiotis Kanavos Jan 14 '21 at 13:10