寻找一种将价格解析为十进制的通用方法

问题描述 投票:6回答:2

我正在开展一个我需要解析价格的项目。我必须考虑不同的价格格式。

问题:

美国公民以这种方式写价格:1,000.00

欧盟这种方式:1.000,00

这个问题可以解决使用逗号和点分割字符串,所以列表中的最后一项是美分。问题在于,有时人们根本不写分数,所以有人可以写1.000欧元。

还有其他问题......有时人们根本不写点。

你知道一些python模块或功能可以解决这个问题,并返回价格的decimal.Decimal?我不关心货币。

编辑:假设我将以这种格式提供数千种价格。

python python-2.7 parsing
2个回答
2
投票

此代码使用此逻辑:

  • 如果不 '。'或','存在,只是转换为浮动
  • 否则如果','或'。'是结尾的第3个字符,那么这是十进制字符: 。 strip然后是非十进制字符,将十进制char更改为'。'如有必要,然后转换为浮动
  • 其他 。没有给出小数部分,只需删除所有','和'。'并转换为浮动

此代码非常依赖于获取有效字符串 - 无效字符串(如"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

0
投票

使用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)
© www.soinside.com 2019 - 2024. All rights reserved.