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
9 changes: 9 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
Babel Changelog
===============

Version 2.19.0 (Unreleased)
----------------------------

Bugfixes
~~~~~~~~

* Numbers: Raise ``NumberFormatError`` instead of ``decimal.InvalidOperation``
when formatting an invalid string value by @2025sl93041-gkb in :gh:`702`

Version 2.18.0
--------------

Expand Down
10 changes: 8 additions & 2 deletions babel/numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,10 @@ def _get_compact_format(
https://www.unicode.org/reports/tr35/tr35-45/tr35-numbers.html#Compact_Number_Formats.
"""
if not isinstance(number, decimal.Decimal):
number = decimal.Decimal(str(number))
try:
number = decimal.Decimal(str(number))
except decimal.InvalidOperation as e:
raise NumberFormatError(f"{number!r} is not a valid number") from e
if number.is_nan() or number.is_infinite():
return number, None
format = None
Expand Down Expand Up @@ -1477,7 +1480,10 @@ def apply(
:raise UnsupportedNumberingSystemError: If the numbering system is not supported by the locale.
"""
if not isinstance(value, decimal.Decimal):
value = decimal.Decimal(str(value))
try:
value = decimal.Decimal(str(value))
except decimal.InvalidOperation as e:
raise NumberFormatError(f"{value!r} is not a valid number") from e

value = value.scaleb(self.scale)

Expand Down
7 changes: 7 additions & 0 deletions tests/test_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -695,3 +695,10 @@ def test_issue_1076_fixes():
assert numbers.format_compact_decimal(2345678, format_type="long", locale="ja") == "235万"
# Swahili does not define an accounting currency format; root aliases it to the standard format.
assert numbers.format_currency(-2, "USD", format_type="accounting", locale="sw") == "-US$\xa02.00"


def test_number_pattern_apply_invalid_string_raises_number_format_error():
from unittest.mock import MagicMock
pattern = numbers.parse_pattern('0.###')
with pytest.raises(numbers.NumberFormatError, match="is not a valid number"):
pattern.apply('not_a_number', locale=MagicMock())