Skip to content

Handle integers larger than a float in scientific - #426

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

itzzdev09 wants to merge 1 commit 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).

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

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