我刚刚从Format numbers as currency in Python了解到Python模块babel提供{a3}来将数字格式化为货币。例如
from babel.numbers import format_currency
s = format_currency(123456.789, 'USD', locale='en_US') # u'$123,456.79'
s = format_currency(123456.789, 'EUR', locale='fr_FR') # u'123\xa0456,79\xa0\u20ac'
反过来呢,从货币到数字,比如$123,456,789.00
-->;123456789
?babel
提供^{parse_currency
的内容。那么,将本币解析成数字的理想方法是什么?在
我通过了Python: removing characters except digits from string。在
^{pr2}$它不考虑十进制分隔符.
。在
从字符串中删除除.
之外的所有非数字字符(请参阅here)
import re
# Way 1:
s = '$123,456.79'
n = re.sub("[^0-9|.]", "", s) # 123456.79
# Way 2:
non_decimal = re.compile(r'[^\d.]+')
s = '$123,456.79'
n = non_decimal.sub('', s) # 123456.79
它确实处理十进制分隔符.
。在
但上述解决方案在
from babel.numbers import format_currency
s = format_currency(123456.789, 'EUR', locale='fr_FR') # u'123\xa0456,79\xa0\u20ac'
new_s = s.encode('utf-8') # 123 456,79 €
如你所见,货币的格式各不相同。用一般方法将货币解析为数字的理想方法是什么?
使用巴别塔
babel文档注意到the number parsing is not fully implemented yes,但是他们做了很多工作来将货币信息输入到库中。您可以使用
get_currency_name()
和get_currency_symbol()
获取货币详细信息,还可以使用所有其他get_...
函数来获取正常数字的详细信息(小数点、减号等)。在使用这些信息,您可以从货币字符串中排除货币详细信息(名称、符号)和分组(例如美国的
,
)。然后将十进制细节更改为C
区域设置使用的细节(-
表示减号,.
表示小数点)。在这就产生了以下代码(我添加了一个对象来保存一些数据,这在进一步处理时可能会很方便):
输出看起来很有希望(在美国地区):
^{pr2}$它仍然适用于不同的地区(巴西以逗号作为小数点而著名):
值得指出的是,})。在
babel
存在一些编码问题。这是因为区域设置文件(在locale-data
)本身确实使用不同的编码。如果你在处理你熟悉的货币,那应该不是问题。但如果你尝试不熟悉的货币,你可能会遇到问题(我刚刚了解到波兰使用iso-8859-2
,而不是{相关问题 更多 >
编程相关推荐