Skip to content

Commit 29b4e1e

Browse files
author
Vinayak Deshmuk
committed
Fix metric() rounding carry stopping at quetta
Closes #423
1 parent 392aef7 commit 29b4e1e

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

‎src/humanize/number.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -579,11 +579,16 @@ def metric(value: float, unit: str = "", precision: int = 3) -> str:
579579
return scientific(value, precision - 1) + unit
580580

581581
old_bucket = exponent // 3 * 3
582+
original_value = value
582583
value /= 10**old_bucket
583584
digits = int(max(0, precision - exponent % 3 - 1))
584585
# Absorb a rounding carry (9.999 -> 10.0) by bumping the exponent.
585-
if exponent < 30 and round(abs(value), digits) >= 10 ** (exponent % 3 + 1):
586+
if round(abs(value), digits) >= 10 ** (exponent % 3 + 1):
586587
exponent += 1
588+
if exponent >= 33:
589+
# Carried past the largest SI prefix (quetta); fall back to
590+
# scientific notation (see #423).
591+
return scientific(original_value, precision - 1) + unit
587592
new_bucket = exponent // 3 * 3
588593
value /= 10 ** (new_bucket - old_bucket)
589594
digits = int(max(0, precision - exponent % 3 - 1))

‎tests/test_number.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,3 +377,24 @@ def test_clamp(test_args: list[typing.Any], expected: str) -> None:
377377
)
378378
def test_metric(test_args: list[typing.Any], expected: str) -> None:
379379
assert humanize.metric(*test_args) == expected
380+
381+
382+
@pytest.mark.parametrize(
383+
"test_args, expected",
384+
[
385+
([9.996e30], "10.0 Q"),
386+
([9.996e31], "100 Q"),
387+
([9.996e32], "1.00 x 10³³"),
388+
([9.996e32, "W"], "1.00 x 10³³W"),
389+
([1e33], "1.00 x 10³³"),
390+
],
391+
ids=str,
392+
)
393+
def test_metric_rounding_carry_at_quetta(
394+
test_args: list[typing.Any], expected: str
395+
) -> None:
396+
# https://github.com/python-humanize/humanize/issues/423
397+
# The rounding carry stopped at exponent 30 (quetta): values rounding up
398+
# kept too many digits, and values rounding past quetta were not moved to
399+
# scientific notation.
400+
assert humanize.metric(*test_args) == expected

0 commit comments

Comments
 (0)