Skip to content

metric: handle rounding carry at the quetta boundary - #485

Closed
mayur-dhavan wants to merge 2 commits into
python-humanize:mainfrom
mayur-dhavan:fix-metric-quetta-carry
Closed

mayur-dhavan wants to merge 2 commits into
python-humanize:mainfrom
mayur-dhavan:fix-metric-quetta-carry

Conversation

@mayur-dhavan

Copy link
Copy Markdown

Fixes #423.

Problem

metric() absorbs a rounding carry (9999 -> 10.0 k) by bumping the exponent, but the carry check was guarded by exponent < 30, so at the quetta boundary the mantissa gained a digit instead:

>>> humanize.metric(9.996e30)
'10.00 Q'    # before -> '10.0 Q' after
>>> humanize.metric(9.996e31)
'100.0 Q'    # before -> '100 Q' after
>>> humanize.metric(9.996e32)
'1000 Q'     # before -> '1.00 x 10³³' after (no prefix above quetta)

Fix

Drop the exponent < 30 guard so the carry logic applies to every bucket, and when the bump pushes the exponent to 33 (past quetta, where no larger SI prefix exists), fall back to scientific(), matching the documented behavior for values beyond the prefix range. The negative-exponent side (quecto) already worked and is covered by a new regression case.

Tests

Five new parametrized cases in test_metric: 9.996e30 -> 10.0 Q, 9.996e31 -> 100 Q, 9.996e32 -> 1.00 x 10³³, 9.999e-30 -> 10.0 q, -9.996e31 -> -100 Q. tests/test_number.py passes locally (246 passed) and the full suite passes except the pre-existing test_benchmarks.py collection errors, which require the optional pytest-benchmark plugin and fail identically on unmodified master.

AI disclosure: this contribution was prepared with AI assistance (an automated coding agent acting on behalf of the author); the change and tests were validated locally against the project's test suite as described above.

Remove unnecessary condition for rounding carry in number formatting.
Add test cases for rounding carry at quetta boundary.
Copilot AI balanced review requested due to automatic review settings October 25, 2026 18:42

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@mayur-dhavan

Copy link
Copy Markdown
Author

Closing this as a duplicate of #424 (Oct 1), which fixes #423 with the same boundary handling and identical expected outputs (10.0 Q, 100 Q, 1.00 x 10³³). I missed it when checking for existing work. Sorry for the noise.

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.

metric() adds a digit when a value rounds into quetta

2 participants