Looking for a universal way to parse the decimal price

I am working on a project where I have to sort prices. I have to consider different price formats.

Problems:

US citizens write prices this way: 1,000.00

EU as follows: 1.000,00

This problem can be solved by separating the line with commas and periods, so the last item in the list will be cents. The problem is that sometimes people don’t write cents at all, so someone can write, for example, 1.000 EUR.

And there are other problems ... sometimes people don’t write dots at all.

Do you know any python module or function that could solve this problem and return decimal.Decimal prices? I don't care about the currency.

EDIT: Suppose I have thousands of prices in such formats.

+6
source share
2 answers

This code uses this logic:

  • if not. or ',' are present, just convert to float
  • else if ',' or '.' are the third character from the end, then this is a decimal character:

    . strip and then not a decimal character, change the decimal char character to '.' if necessary, then convert to float

  • yet

    . there is no decimal part, just separate all "," and ".". and convert to float

This code is very dependent on getting valid strings - invalid strings like "1,2,3.000" or "1..." will give erroneous values.

 def parse_price(s): if '.' not in s and ',' not in s: return float(s) elif s[-3] in ',.': dec_char = s[-3] sep_char = {'.': ',', ',':'.'}[dec_char] s = s.replace(sep_char, '') s = s.replace(',', '.') return float(s) else: s = s.replace(',','').replace('.', '') return float(s) tests = """\ 1.000 1.000,20 23.14 1,234 1.23 3,12 """.splitlines() for test in tests: print(test, '->', parse_price(test)) 

gives

 1.000 -> 1000.0 1.000,20 -> 1000.2 23.14 -> 23.14 1,234 -> 1234.0 1.23 -> 1.23 3,12 -> 3.12 
+2
source

Use the price parser :

 >>> from price_parser import parse_price >>> parse_price('1,000.00') Price(amount=Decimal('1000.00'), currency=None) >>> parse_price('1.000,00') Price(amount=Decimal('1000.00'), currency=None) 
0
source

Source: https://habr.com/ru/post/1012979/


All Articles