Skip to content
Open
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
57 changes: 54 additions & 3 deletions babel/numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1189,6 +1189,13 @@ def parse_decimal(
locale = Locale.parse(locale or LC_NUMERIC)
group_symbol = get_group_symbol(locale, numbering_system=numbering_system)
decimal_symbol = get_decimal_symbol(locale, numbering_system=numbering_system)
minus_sign = get_minus_sign_symbol(locale, numbering_system=numbering_system)

# Accept the locale's minus sign (e.g. U+2212 for 'fi') as well as the
# ASCII hyphen-minus. Only the leading sign is normalized; the rest of
# the string is left untouched.
if minus_sign != '-' and string.startswith(minus_sign):
string = '-' + string[len(minus_sign) :]

if not strict and (
group_symbol in SPACE_CHARS # if the grouping symbol is a kind of space,
Expand All @@ -1210,7 +1217,13 @@ def parse_decimal(
decimal_quantization=False,
numbering_system=numbering_system,
)
if string != proper and proper != _remove_trailing_zeros_after_decimal(string, decimal_symbol): # fmt: skip
# The input minus sign was normalized to '-' above; compare against
# the properly formatted number with its minus sign normalized the
# same way, so ASCII '-' and the locale's minus sign are equivalent.
proper_comparable = proper
if minus_sign != '-' and proper.startswith(minus_sign):
proper_comparable = '-' + proper[len(minus_sign) :]
if string != proper_comparable and proper_comparable != _remove_trailing_zeros_after_decimal(string, decimal_symbol): # fmt: skip
try:
parsed_alt = decimal.Decimal(
string.replace(decimal_symbol, '').replace(group_symbol, '.'),
Expand Down Expand Up @@ -1304,6 +1317,34 @@ def parse_grouping(p: str) -> tuple[int, int]:
return g1, g2


def _replace_unquoted_minus_sign(text: str, minus_sign: str) -> str:
"""Replace unquoted ``-`` characters with the locale's minus sign.

In a number pattern, a bare ``-`` stands for the minus sign symbol,
while a ``-`` inside single quotes is literal text and is left alone.
"""
if '-' not in text or minus_sign == '-':
return text
result = []
in_quotes = False
i = 0
while i < len(text):
char = text[i]
if char == "'":
if text[i : i + 2] == "''":
result.append("''")
i += 2
continue
in_quotes = not in_quotes
result.append(char)
elif char == '-' and not in_quotes:
result.append(minus_sign)
else:
result.append(char)
i += 1
return ''.join(result)


def parse_pattern(pattern: NumberPattern | str) -> NumberPattern:
"""Parse number format patterns"""
if isinstance(pattern, NumberPattern):
Expand Down Expand Up @@ -1554,11 +1595,21 @@ def apply(
numbering_system=numbering_system,
)

# A bare '-' in the negative prefix or suffix stands for the
# locale's minus sign symbol (e.g. U+2212 for 'fi'); a quoted '-'
# is literal text and is left alone.
prefix = self.prefix[is_negative]
suffix = self.suffix[is_negative]
if is_negative:
minus_sign = get_minus_sign_symbol(locale, numbering_system=numbering_system)
prefix = _replace_unquoted_minus_sign(prefix, minus_sign)
suffix = _replace_unquoted_minus_sign(suffix, minus_sign)

retval = ''.join(
(
self.prefix[is_negative],
prefix,
number if self.number_pattern != '' else '',
self.suffix[is_negative],
suffix,
),
)

Expand Down
39 changes: 39 additions & 0 deletions tests/test_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,25 @@ def test_format_decimal():
numbers.format_decimal(12345.5, locale='en_US', numbering_system="unknown")


def test_format_decimal_uses_locale_minus_sign():
# Locales whose CLDR minus sign is not ASCII '-' use that symbol, and
# the mantissa and exponent of a scientific number agree on it.
assert numbers.format_decimal(-1234.5, locale='fi') == '\u22121\xa0234,5'
assert numbers.format_decimal(-1234.5, locale='sv') == '\u22121\xa0234,5'
assert numbers.format_decimal(-1234.5, locale='he') == '\u200e-1,234.5'
assert numbers.format_decimal(-1234.5, locale='ar') == '\u200e-1,234.5'
assert numbers.format_decimal(-1.23e-4, locale='fi', format='#.##E0') == (
'\u22121,23E\u22124'
)
# Locales with an ASCII minus sign are unaffected.
assert numbers.format_decimal(-1234.5, locale='en_US') == '-1,234.5'
assert numbers.format_decimal(-1234.5, locale='de') == '-1.234,5'
# An explicitly quoted '-' in the pattern is literal text, not the
# minus sign, while an unquoted '-' in the negative subpattern is.
assert numbers.format_decimal(-1.5, "#,##0.00;'-'#,##0.00", locale='fi') == '-1,50'
assert numbers.format_decimal(-1.5, "#,##0.00;-#,##0.00", locale='fi') == '\u22121,50'


@pytest.mark.parametrize(('input_value', 'expected_value'), [
('10000', '10,000'),
('1', '1'),
Expand Down Expand Up @@ -565,6 +584,26 @@ def test_parse_decimal():
numbers.parse_decimal('2,109,998', locale='de')


def test_parse_decimal_accepts_locale_minus_sign():
# Both the locale's minus sign and the ASCII hyphen-minus parse, and
# they are equivalent in strict mode.
assert numbers.parse_decimal('\u22121\xa0234,5', locale='fi') == decimal.Decimal('-1234.5')
assert numbers.parse_decimal('-1\xa0234,5', locale='fi') == decimal.Decimal('-1234.5')
assert numbers.parse_decimal('\u22121\xa0234,5', locale='fi', strict=True) == (
decimal.Decimal('-1234.5')
)
assert numbers.parse_decimal('-1\xa0234,5', locale='fi', strict=True) == (
decimal.Decimal('-1234.5')
)
assert numbers.parse_decimal('\u200e-1,234.5', locale='he') == decimal.Decimal('-1234.5')
# Round-trip through the locale's own formatting.
for locale in ['fi', 'sv', 'he', 'ar', 'en_US', 'de']:
value = decimal.Decimal('-1234.5')
assert numbers.parse_decimal(numbers.format_decimal(value, locale=locale), locale=locale) == value
assert numbers.parse_decimal(
numbers.format_decimal(value, locale=locale), locale=locale, strict=True) == value


@pytest.mark.parametrize(
'string',
[
Expand Down