Skip to content

Keep three digits when metric rounds into quetta - #424

Open
SashaMIT wants to merge 1 commit into
python-humanize:mainfrom
SashaMIT:metric-quetta-digits
Open

SashaMIT wants to merge 1 commit into
python-humanize:mainfrom
SashaMIT:metric-quetta-digits

Conversation

@SashaMIT

@SashaMIT SashaMIT commented Oct 1, 2026 •

Copy link
Copy Markdown

Fixes #423

Changes proposed in this pull request:

  • metric(9.996e30) returned 10.00 Q. 9999 is already 10.0 k, not 10.00 k. This is now 10.0 Q.
  • metric(9.996e31) returned 100.0 Q. It is now 100 Q.
  • metric(9.996e32) returned 1000 Q. There is no prefix past quetta, so this is now 1.00 x 10³³.
  • 2.596e32 is still 260 QF. A negative value keeps its sign.

pytest tests/test_number.py (248 passed).

The carry that keeps three digits stopped at exponent 30, so 9.996e30 printed 10.00 Q.

@ub3dqy ub3dqy 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.

Checked on Windows/Python 3.14.2. The existing 248 number tests pass. I found one zero-precision regression below; the suggested guard passes those tests plus 30 carry/precision checks.

Dima Mak / ub3dqy

Comment thread src/humanize/number.py
if round(abs(value), digits) >= 10 ** (exponent % 3 + 1):
exponent += 1
if exponent >= 33:
return scientific(original, precision - 1) + unit

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

metric() already accepts precision=0 (including cases in the existing test table), but this new branch passes -1 to scientific():

humanize.metric(9.996e32, precision=0)
# ValueError: Format specifier missing precision

The base commit returns 1000 Q for this input. Negative values and calls with a unit are affected too. Clamping the decimal precision here preserves zero precision when switching to scientific notation:

Suggested change
return scientific(original, precision - 1) + unit
return scientific(original, max(0, precision - 1)) + unit

I checked positive/negative values, unit/no unit, and precisions 0, 1, 2, 3 and 6: all 30 additional cases pass with this guard, alongside the 248 existing number tests. Four of those cases raise on the current PR head.

Dima Mak / ub3dqy

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