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
38 changes: 35 additions & 3 deletions babel/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@
from typing import Literal

from babel.core import Locale
from babel.numbers import LC_NUMERIC, format_decimal
from babel.numbers import (
LC_NUMERIC,
NumberPattern,
format_decimal,
get_decimal_precision,
get_decimal_quantum,
parse_pattern,
)

_DEPRECATED_UNIT_IDS: dict[str, str] = {
# Unit IDs deprecated in CLDR 48
Expand Down Expand Up @@ -97,6 +104,30 @@ def _find_unit_pattern(unit_id: str, locale: Locale | str | None = None) -> str
return None


def _get_displayed_number(
value: float | decimal.Decimal,
pattern: NumberPattern,
) -> float | decimal.Decimal:
"""Return `value` rounded the way the number pattern displays it.

The plural form of a unit pattern is chosen from the formatted number, so
e.g. ``0.9999`` displayed as "1" takes the "one" form, and ``1`` displayed
as "1.00" takes the "other" form in English.
Significant-digit and scientific patterns keep using the original value.
"""
if pattern.exp_prec or '@' in pattern.pattern:
return value
number = value if isinstance(value, decimal.Decimal) else decimal.Decimal(str(value))
if not number.is_finite():
return value
# This mirrors the rounding done by `NumberPattern.apply()`.
number = abs(number.scaleb(pattern.scale)).normalize()
min_frac, max_frac = pattern.frac_prec
number = number.quantize(get_decimal_quantum(max_frac))
# Trailing fractional zeros are only displayed down to the minimum precision.
return number.quantize(get_decimal_quantum(max(min_frac, get_decimal_precision(number))))


def format_unit(
value: str | float | decimal.Decimal,
measurement_unit: str,
Expand Down Expand Up @@ -167,13 +198,14 @@ def format_unit(
formatted_value = value
plural_form = "one"
else:
pattern = parse_pattern(locale.decimal_formats[None] if format is None else format)
formatted_value = format_decimal(
value,
format,
pattern,
locale,
numbering_system=numbering_system,
)
plural_form = locale.plural_form(value)
plural_form = locale.plural_form(_get_displayed_number(value, pattern))

length_patterns = locale._data["unit_patterns"][q_unit].get(length, {}) # resolves aliases
# Fall back from the correct plural form to "other"
Expand Down
23 changes: 23 additions & 0 deletions tests/test_units.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from decimal import Decimal
from functools import partial

import pytest
Expand Down Expand Up @@ -39,6 +40,28 @@ def test_issue_1217(count, unit, locale, length, expected):
assert format_unit(count, unit, length, locale=locale) == expected


@pytest.mark.parametrize(
('count', 'unit', 'locale', 'format', 'expected'),
[
# The plural form is chosen from the number as displayed (as in ICU).
(0.9999, 'length-meter', 'en', None, '1 meter'),
(Decimal('1.0'), 'length-meter', 'en', None, '1 meter'),
(2.0001, 'length-meter', 'pl', None, '2 metry'),
(4.9999, 'duration-hour', 'ru', None, '5 часов'),
(Decimal('21.0'), 'duration-day', 'ru', None, '21 день'),
(1.04, 'length-meter', 'en', '#,##0.0', '1.0 meters'),
(1.04, 'length-meter', 'en', '@@', '1.0 meters'),
(12345, 'length-meter', 'en', '#E0', '1.2345E4 meters'),
(2, 'length-meter', 'pl', None, '2 metry'),
(1.5, 'length-meter', 'pl', None, '1,5 metra'),
(1, 'length-meter', 'en', '#,##0.00', '1.00 meters'),
('1.0', 'length-meter', 'en', None, '1.0 meter'),
],
)
def test_format_unit_plural_from_displayed_number(count, unit, locale, format, expected):
assert format_unit(count, unit, format=format, locale=locale) == expected


@pytest.mark.parametrize(('unit_id', 'replacement'), _DEPRECATED_UNIT_IDS.items())
def test_deprecated_unit_ids(unit_id, replacement):
for func in (partial(format_unit, 1), get_unit_name):
Expand Down