我正在开展一个我需要解析价格的项目。我必须考虑不同的价格格式。
问题:
美国公民以这种方式写价格:1,000.00
欧盟这种方式:1.000,00
这个问题可以解决使用逗号和点分割字符串,所以列表中的最后一项是美分。问题在于,有时人们根本不写分数,所以有人可以写1.000欧元。
还有其他问题......有时人们根本不写点。
你知道一些python模块或功能可以解决这个问题,并返回价格的decimal.Decimal
?我不关心货币。
编辑:假设我将以这种格式提供数千种价格。
此代码使用此逻辑:
此代码非常依赖于获取有效字符串 - 无效字符串(如"1,2,3.000"
或"1..."
)将给出错误的值。
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))
给
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
使用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)