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.

2
  • 2
    More elegant than what? You didn't post a solution. Commented Jun 11, 2017 at 18:59
  • Possible duplicate of convert decimal mark Commented Jun 11, 2017 at 19:04

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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(",","."))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.