diff --git a/src/humanize/__init__.py b/src/humanize/__init__.py index 4f54bc46..c40cafb0 100644 --- a/src/humanize/__init__.py +++ b/src/humanize/__init__.py @@ -22,6 +22,8 @@ intword, metric, ordinal, + percentage, + ratio, scientific, ) from humanize.time import ( @@ -52,7 +54,9 @@ "naturalsize", "naturaltime", "ordinal", + "percentage", "precisedelta", + "ratio", "scientific", "thousands_separator", ] diff --git a/src/humanize/number.py b/src/humanize/number.py index e5a2612d..707f8dfb 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -536,6 +536,139 @@ def clamp( raise ValueError(msg) +def percentage(value: NumberOrString, ndigits: int | None = None) -> str: + """Converts a ratio (decimal) to a percentage string. + + For example, 0.75 becomes "75%", 0.5 becomes "50%". Works for any float or + anything that can be converted to a float. Values over 1 are supported (e.g., + 1.5 becomes "150%"). Large percentages use thousand separators. + + Examples: + ```pycon + >>> percentage(0.75) + '75%' + >>> percentage(0.5) + '50%' + >>> percentage(0.333, 1) + '33.3%' + >>> percentage(1.5) + '150%' + >>> percentage(12345.6) + '1,234,560%' + >>> percentage(-0.25) + '-25%' + >>> percentage(0) + '0%' + >>> percentage("0.1") + '10%' + >>> percentage(None) + 'None' + >>> percentage("foo") + 'foo' + + ``` + + Args: + value (float, str): Ratio to convert (0.5 = 50%). + ndigits (int, None): Digits of precision after the decimal point. + If None, preserves original precision. + + Returns: + str: Percentage string with '%' suffix. + """ + import math + + try: + if isinstance(value, str): + value = float(value) + if not math.isfinite(value): + return _format_not_finite(value) + value = float(value) + except (TypeError, ValueError): + return str(value) + + pct_value = round(value * 100, 10) + + if ndigits is not None: + result = intcomma(round(pct_value, ndigits), ndigits) + elif pct_value == int(pct_value): + result = intcomma(int(pct_value)) + else: + result = intcomma(pct_value) + + return f"{result}%" + + +def ratio( + numerator: NumberOrString, + denominator: NumberOrString, + ndigits: int = 2, +) -> str: + """Formats a ratio of two numbers as a fraction string. + + For example, (3, 4) becomes "3/4", (1000, 2000) becomes "1,000/2,000". + Large numbers use thousand separators. Floats are rounded to the specified + precision. + + Examples: + ```pycon + >>> ratio(3, 4) + '3/4' + >>> ratio(1, 2) + '1/2' + >>> ratio(1000, 2000) + '1,000/2,000' + >>> ratio(1.555, 3, 1) + '1.6/3' + >>> ratio(0, 10) + '0/10' + >>> ratio("3", "4") + '3/4' + >>> ratio(None, 5) + 'None' + + ``` + + Args: + numerator (float, str): The numerator of the ratio. + denominator (float, str): The denominator of the ratio. + ndigits (int): Digits of precision for rounding floats. Defaults to 2. + + Returns: + str: Ratio string in the form "numerator/denominator". + + Raises: + ValueError: If denominator is zero. + """ + import math + + try: + num = float(numerator) + except (TypeError, ValueError): + return str(numerator) + + try: + denom = float(denominator) + except (TypeError, ValueError): + return str(denominator) + + if not math.isfinite(num): + return _format_not_finite(num) + if not math.isfinite(denom): + return _format_not_finite(denom) + + if denom == 0: + msg = "division by zero" + raise ValueError(msg) + + def format_number(val: float) -> str: + if val == int(val): + return intcomma(int(val)) + return intcomma(round(val, ndigits), ndigits) + + return f"{format_number(num)}/{format_number(denom)}" + + def metric(value: float, unit: str = "", precision: int = 3) -> str: """Return a value with a metric SI unit-prefix appended. diff --git a/tests/test_number.py b/tests/test_number.py index 5fb12fa6..4ec64b79 100644 --- a/tests/test_number.py +++ b/tests/test_number.py @@ -377,3 +377,104 @@ def test_clamp(test_args: list[typing.Any], expected: str) -> None: ) def test_metric(test_args: list[typing.Any], expected: str) -> None: assert humanize.metric(*test_args) == expected + + +@pytest.mark.parametrize( + "test_args, expected", + [ + # Basic cases + ([0.75], "75%"), + ([0.5], "50%"), + ([0.25], "25%"), + ([0], "0%"), + ([1], "100%"), + # Over 100% + ([1.5], "150%"), + ([2], "200%"), + # Negative + ([-0.25], "-25%"), + ([-1], "-100%"), + # Precision + ([0.333, 1], "33.3%"), + ([0.3333, 2], "33.33%"), + ([0.33333, 0], "33%"), + # Large percentages (uses intcomma) + ([12345.6], "1,234,560%"), + ([100], "10,000%"), + # Small values + ([0.001], "0.1%"), + ([0.0001], "0.01%"), + ([0.001, 0], "0%"), + # String input + (["0.5"], "50%"), + (["0.1"], "10%"), + # Edge cases + ([None], "None"), + (["foo"], "foo"), + ([math.nan], "NaN"), + ([math.inf], "+Inf"), + ([-math.inf], "-Inf"), + # Near 100% + ([0.999], "99.9%"), + ([0.9999, 2], "99.99%"), + # Floating point precision + ([0.29], "29%"), + ([1.1], "110%"), + ([0.1 + 0.2], "30%"), + ], +) +def test_percentage(test_args: list[typing.Any], expected: str) -> None: + assert humanize.percentage(*test_args) == expected + + +@pytest.mark.parametrize( + "test_args, expected", + [ + # Basic cases + ([3, 4], "3/4"), + ([1, 2], "1/2"), + ([0, 10], "0/10"), + ([10, 10], "10/10"), + # Over 100% + ([15, 10], "15/10"), + # Large numbers (uses intcomma) + ([1000, 2000], "1,000/2,000"), + ([1_000_000, 2_000_000], "1,000,000/2,000,000"), + # Floats with rounding + ([1.555, 3, 1], "1.6/3"), + ([1.5, 3], "1.50/3"), # ndigits=2 by default + ([1.555, 3.777, 2], "1.55/3.78"), # 1.555 rounds to 1.55 with banker's rounding + # Negative values + ([-5, 10], "-5/10"), + ([5, -10], "5/-10"), + ([-5, -10], "-5/-10"), + # String input + (["3", "4"], "3/4"), + (["1.5", "3"], "1.50/3"), # ndigits=2 by default + # Edge cases + ([None, 5], "None"), + ([5, None], "None"), + (["foo", 5], "foo"), + ([5, "bar"], "bar"), + ([math.nan, 5], "NaN"), + ([5, math.nan], "NaN"), + ([math.inf, 5], "+Inf"), + ([5, math.inf], "+Inf"), + ([-math.inf, 5], "-Inf"), + # Integers stay as integers + ([3.0, 4.0], "3/4"), + ([1.0, 2.0], "1/2"), + ], +) +def test_ratio(test_args: list[typing.Any], expected: str) -> None: + assert humanize.ratio(*test_args) == expected + + +def test_ratio_division_by_zero() -> None: + with pytest.raises(ValueError, match="division by zero"): + humanize.ratio(1, 0) + + +def test_ratio_both_zero() -> None: + with pytest.raises(ValueError, match="division by zero"): + humanize.ratio(0, 0)