Skip to content

Handle integers larger than a float in scientific - #426

Open
itzzdev09 wants to merge 2 commits into
python-humanize:mainfrom
itzzdev09:fix/scientific-large-int
Open

itzzdev09 wants to merge 2 commits into
python-humanize:mainfrom
itzzdev09:fix/scientific-large-int

Conversation

@itzzdev09

Copy link
Copy Markdown

Fixes #

Changes proposed in this pull request:

  • scientific falls back to Decimal formatting when float() overflows, so an integer larger than the float range no longer raises OverflowError
  • Behaviour for every other input (floats, strings, NaN/Inf, small ints) is unchanged, since Decimal is only used on the overflow path
  • Tests for 10**400, its negative, a precision argument and precision 0, plus 0 to pin the unchanged path

Same family as #420: scientific converts with float() first, which raises OverflowError for an integer beyond the float range and is not covered by the except (ValueError, TypeError) clause.

>>> humanize.scientific(10**400)
OverflowError: int too large to convert to float

After this change it returns '1.00 x 10⁴⁰⁰'.

Decimal is not used for all integers because format(Decimal(0), ".2e") gives 0.00e+2, which would break scientific(0).

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

The integer overflow case is fixed, but the same finite value passed through the accepted string input still renders as infinity: scientific(10**400) → 1.00 x 10⁴⁰⁰, while scientific("1" + "0" * 400) → +Inf. I reproduced both at this head. float(huge_integer_string) returns infinity rather than raising OverflowError, so the Decimal fallback is skipped for that form. Consider an integer-string regression and detecting that finite form before the float conversion. I ran these checks on Python 3.12 with English locale hooks; no full package test run.

float() turns a numeric string that is too large into infinity and one
that is too small into zero, so scientific() rendered '1' followed by 400
zeros as +Inf and '1e-400' as 0. Format such strings with Decimal.
@itzzdev09

Copy link
Copy Markdown
Author

Thanks, fixed in 40a2faf: numeric strings beyond float range (both too large and too small, e.g. "1" + "0" * 400 and "1e-400") now go through Decimal, with tests for both.

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