def parse_decimal(string, locale=LC_NUMERIC):
"""Parse localized decimal string into a decimal.
>>> parse_decimal('1,099.98', locale='en_US')
Decimal('1099.98')
>>> parse_decimal('1.099,98', locale='de')
Decimal('1099.98')
When the given string cannot be parsed, an exception is raised:
>>> parse_decimal('2,109,998', locale='de')
Traceback (most recent call last):
...
NumberFormatError: '2,109,998' is not a valid decimal number
:param string: the string to parse
:param locale: the `Locale` object or locale identifier
:raise NumberFormatError: if the string can not be converted to a
decimal number
"""
locale = Locale.parse(locale)
try:
return Decimal(string.replace(get_group_symbol(locale), '')
.replace(get_decimal_symbol(locale), '.'))
except InvalidOperation:
raise NumberFormatError('%r is not a valid decimal number' % string)
评论列表
文章目录