Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions babel/numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,8 @@ def parse_decimal(string, locale=LC_NUMERIC, strict=False):
Decimal('1099.98')
>>> parse_decimal('1.099,98', locale='de')
Decimal('1099.98')
>>> parse_decimal('12 345,123', locale='ru')
Decimal('12345.123')

When the given string cannot be parsed, an exception is raised:

Expand Down Expand Up @@ -704,6 +706,15 @@ def parse_decimal(string, locale=LC_NUMERIC, strict=False):
locale = Locale.parse(locale)
group_symbol = get_group_symbol(locale)
decimal_symbol = get_decimal_symbol(locale)

if not strict and (
group_symbol == u'\xa0' and # if the grouping symbol is U+00A0 NO-BREAK SPACE,
group_symbol not in string and # and the string to be parsed does not contain it,
' ' in string # but it does contain a space instead,
):
# ... it's reasonable to assume it is taking the place of the grouping symbol.
string = string.replace(' ', group_symbol)

try:
parsed = decimal.Decimal(string.replace(group_symbol, '')
.replace(decimal_symbol, '.'))
Expand Down
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ release = sdist bdist_wheel
[tool:pytest]
norecursedirs = venv* .* _* scripts {args}
doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE ALLOW_UNICODE IGNORE_EXCEPTION_DETAIL
markers =
all_locales: parameterize test with all locales

[bdist_wheel]
universal = 1
Expand Down
11 changes: 11 additions & 0 deletions tests/test_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,3 +679,14 @@ def test_numberpattern_repr():
def test_parse_static_pattern():
assert numbers.parse_pattern('Kun') # in the So locale in CLDR 30
# TODO: static patterns might not be correctly `apply()`ed at present


def test_parse_decimal_nbsp_heuristics():
# Re https://github.com/python-babel/babel/issues/637 –
# for locales (of which there are many) that use U+00A0 as the group
# separator in numbers, it's reasonable to assume that input strings
# with plain spaces actually should have U+00A0s instead.
# This heuristic is only applied when strict=False.
n = decimal.Decimal("12345.123")
assert numbers.parse_decimal("12 345.123", locale="fi") == n
assert numbers.parse_decimal(numbers.format_decimal(n, locale="fi"), locale="fi") == n