Skip to content

Fix ValueError in metric()/scientific() with precision 0 - #352

Closed
santhreal wants to merge 2 commits into
python-humanize:mainfrom
santhreal:fix/scientific-negative-precision
Closed

Fix ValueError in metric()/scientific() with precision 0#352
santhreal wants to merge 2 commits into
python-humanize:mainfrom
santhreal:fix/scientific-negative-precision

Conversation

@santhreal

Copy link
Copy Markdown

metric(value, precision=0) raises ValueError: Format specifier missing precision when the magnitude falls back to scientific(), because metric calls scientific(value, precision - 1), so precision 0 becomes -1 and builds an invalid format spec "{:.-1e}". scientific(value, -1) directly hits the same path.

#159 fixed this for the non-scientific metric path; this covers the scientific() fallback it did not reach. scientific now clamps a negative precision to zero.

import humanize
humanize.metric(1e300, "m", 0)   # was: ValueError; now: "1 x 10³⁰⁰m"
humanize.scientific(1e300, -1)   # was: ValueError; now: "1 x 10³⁰⁰"

scientific() built its format spec as f"{{:.{int(precision)}e}}", so a
negative precision produced an invalid spec ("{:.-1e}") and raised
ValueError. This is reachable from the public API through metric(value,
precision=0): for magnitudes that fall back to scientific notation,
metric() calls scientific(value, precision - 1), i.e. scientific(value,
-1). PR python-humanize#159 added the same max(0, ...) clamp to metric()'s main path but
not to scientific(). Clamp the precision to zero.
@santhreal santhreal closed this Jul 28, 2026
@hugovk

hugovk commented Jul 28, 2026

Copy link
Copy Markdown
Member

You've opened many PRs across these repos two weeks ago, and then closed them with no comment:

#352
#353
prettytable/prettytable#483
prettytable/prettytable#484
jazzband/tablib#659
jazzband/tablib#660
jazzband/tablib#661

Please could you explain why?

Also hundreds in other repos:

image

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants