Skip to content

Fix metric() with precision=0 on very large and very small numbers - #544

Open
LemonCondor wants to merge 1 commit into
python-humanize:mainfrom
LemonCondor:fix/metric-zero-precision-scientific
Open

LemonCondor wants to merge 1 commit into
python-humanize:mainfrom
LemonCondor:fix/metric-zero-precision-scientific

Conversation

@LemonCondor

Copy link
Copy Markdown

metric() switches to scientific() for values outside of the SI prefix range (exponent of 33 or more, or below -30) and passes it precision - 1. With precision=0 this is -1, which scientific() turns into an invalid format specifier:

>>> humanize.metric(1500, "W", precision=0)
'2 kW'
>>> humanize.metric(1e50, "W", precision=0)
ValueError: Format specifier missing precision

precision=0 is accepted elsewhere in metric() (the number of decimals is clamped with max(0, ...)) and is covered by the tests, so the fallback now clamps the precision it gives to scientific() the same way: max(precision - 1, 0). The result for precision=1 is unchanged.

Two cases are added to test_metric (1e50 and 1e-50 with precision=0). They fail before the change with the ValueError above, and tests/test_number.py passes after it (243 tests). I ran it with pytest, not through tox.

metric() falls back to scientific() outside of the SI prefix range and
passes it precision - 1. With precision=0 this is -1, which scientific()
turns into an invalid format specifier, so metric(1e50, precision=0)
raised ValueError while metric(1500, precision=0) returned '2 k'.

Keep the precision of the fallback at 0 or more.

Signed-off-by: Guillaume Marty <[email protected]>
@agentscanapp

agentscanapp Bot commented Dec 5, 2026

Copy link
Copy Markdown

Automation signals

Activity patterns show signs of automation.

View full analysis →

Evidence
  • Forks of many different repos: Forks spread across 22 different repositories over 9 days, about 15.5 per week, 19 in the busiest week
  • Fork branch then PR within seconds: 23 fork branches followed by upstream PRs within 81s, out of 25 branches created in total

Last 5 PRs:

This is an automated analysis by AgentScan

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant