Skip to content

Fix format_number producing bogus output for large integers#83

Open
gaoflow wants to merge 1 commit into
xolox:masterfrom
gaoflow:fix-format-number-large-int
Open

Fix format_number producing bogus output for large integers#83
gaoflow wants to merge 1 commit into
xolox:masterfrom
gaoflow:fix-format-number-large-int

Conversation

@gaoflow

@gaoflow gaoflow commented Jun 28, 2026

Copy link
Copy Markdown

format_number() returns corrupted output like '1e,+16' for any integer
>= 10**16. The root cause: str(float(n)) produces scientific notation
for those values (e.g. '1e+16'), then .partition('.') sees no decimal
point and the comma-insertion loop consumes the scientific-notation text
as if it were plain digits.

Before this fix:

>>> format_number(10**16)
'1e,+16'
>>> format_number(10**18)
'1e,+18'

After this fix:

>>> format_number(10**16)
'10,000,000,000,000,000'
>>> format_number(10**18)
'1,000,000,000,000,000,000'

The same bug affects any integer in the [10**16, 10**30) range where
str(float(n)) switches to scientific notation. Beyond that range the
integer literal itself would lose precision in the float conversion.

The fix avoids the unnecessary float() round-trip for plain int
values, preserving the exact decimal string and letting the existing
comma-insertion and sign logic work correctly.

This PR was written with assistance from an AI tool (Claude Code),
under my direction and review.

Closes #NEW (issue not yet filed)

When format_number() receives an integer >= 10**16, str(float(number))
produces scientific notation (e.g. '1e+16'). The subsequent .partition('.')
call then returns ('1e+16', '', '') since there is no decimal point, and
the comma-insertion loop operates on the '1e+...' text as if it were
plain digits, yielding garbage output like '1e,+16'.

Fix by short-circuiting the float conversion for plain int types (using
type(x) is int) and using str(number) directly instead. This preserves
the exact decimal representation and lets the existing comma-insertion
and sign logic work correctly.

Fixes a wrong-results bug where format_number(10**16) returned '1e,+16'
instead of '10,000,000,000,000,000'.
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.

1 participant