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
6 changes: 5 additions & 1 deletion src/humanize/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,7 @@ def metric(value: float, unit: str = "", precision: int = 3) -> str:

if not math.isfinite(value):
return _format_not_finite(value)
original = value
exponent = math.floor(math.log10(abs(value))) if value != 0 else 0

if exponent >= 33 or exponent < -30:
Expand All @@ -582,8 +583,11 @@ def metric(value: float, unit: str = "", precision: int = 3) -> str:
value /= 10**old_bucket
digits = int(max(0, precision - exponent % 3 - 1))
# Absorb a rounding carry (9.999 -> 10.0) by bumping the exponent.
if exponent < 30 and round(abs(value), digits) >= 10 ** (exponent % 3 + 1):
# Quetta still has a prefix for exponents 30 and 31. Exponent 33 does not.
if round(abs(value), digits) >= 10 ** (exponent % 3 + 1):
exponent += 1
if exponent >= 33:
return scientific(original, precision - 1) + unit
new_bucket = exponent // 3 * 3
value /= 10 ** (new_bucket - old_bucket)
digits = int(max(0, precision - exponent % 3 - 1))
Expand Down
7 changes: 7 additions & 0 deletions tests/test_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,13 @@ def test_clamp(test_args: list[typing.Any], expected: str) -> None:
([1.235e29, "A"], "124 RA"),
([2.56e-30, "V"], "2.56 qV"),
([2.596e32, "F"], "260 QF"),
([9.996e30], "10.0 Q"),
([9.996e31], "100 Q"),
([9.996e32], "1.00 x 10³³"),
([-9.996e32], "-1.00 x 10³³"),
([-9.996e30], "-10.0 Q"),
([9.996e30, "V"], "10.0 QV"),
([9.996e32, "F"], "1.00 x 10³³F"),
([1e50], "1.00 x 10⁵⁰"),
([1e-50], "1.00 x 10⁻⁵⁰"),
([-1500, "V"], "-1.50 kV"),
Expand Down