3

I'm new to Python and I was trying to get a "price tag String" to get converted into a float, so I can easily compare the result with other prices. I searched for 2 hours for a answer for this "simple problem", but none of them fitted my needs.

So basically, I have a price like this:

1.222.333,44 EUR

(comma and period swapped because I live in Germany, which is also pretty annoying)

And I want to get this for easy comparing:

1222333.44

The main idea is to compare prices, which is my school project.
I used to do everything with php, which worked, but was way too slow.

If you have a more elegant or simple way, please let me know.

J. Boost
  • 33
  • 3

3 Answers3

8

This work for the specific case you provided:

float(s.replace('.', '').replace(',', '.').split(' ')[0])

It requires:

  1. Periods in price are only separators;
  2. Only one comma in price and is just a decimal mark;
  3. The price comes first and is separated from other strings by a whitespace.

Just to mention in case people need more generalized solution, hiro protagonist's answer using locale is very helpful when you need a simple way to switch between numeral systems during coding or when maintaining your codes.

Y. Luo
  • 5,622
  • 1
  • 18
  • 25
8

you can use your (or any) locale to convert a string to a float:

import locale
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
print(locale.atof('1.222.333,44'))  # -> 1222333.44

depending on your default locale you may not even have to specify the locale.

in your case you may need to split the currency (EUR) part away:

price = '1.222.333,44 EUR'
price_float = locale.atof(price.split()[0])
print(price_float) # -> 1222333.44

note: it may be enough not to setLC_ALL but just LC_NUMERIC to what you need.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0

If your string is "1.222.333,44 EUR"

prince = "1.222.333,44 EUR"
price = price[:-4]
price = price.replace(".","").replace(",",".")
floatprice = float(price)

If it is just like this "1.222.333,44"

floatprice = float("1.222.333,44".replace(".","").replace(",","."))
PythonProgrammi
  • 22,305
  • 3
  • 41
  • 34