Skip to content

Commit 40a2faf

Browse files
committed
Format numeric strings beyond float range in scientific()
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.
1 parent 43145be commit 40a2faf

2 files changed

Lines changed: 13 additions & 4 deletions

File tree

‎src/humanize/number.py‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -442,21 +442,26 @@ def scientific(value: NumberOrString, precision: int = 2) -> str:
442442
str: Number in scientific notation z.wq x 10ⁿ.
443443
"""
444444
import math
445+
from decimal import Decimal
445446

446447
fmt = f"{{:.{int(precision)}e}}"
447448
try:
448449
number = float(value)
449450
except OverflowError:
450451
# An integer beyond float's range: Decimal has no such limit.
451-
from decimal import Decimal
452-
453452
n = fmt.format(Decimal(value))
454453
except (ValueError, TypeError):
455454
return str(value)
456455
else:
457-
if not math.isfinite(number):
456+
out_of_range = number == 0 or not math.isfinite(number)
457+
exact = Decimal(value) if isinstance(value, str) and out_of_range else None
458+
if exact is not None and exact.is_finite() and exact != 0:
459+
# float() turns a string beyond its range into infinity or zero.
460+
n = fmt.format(exact)
461+
elif not math.isfinite(number):
458462
return _format_not_finite(number)
459-
n = fmt.format(number)
463+
else:
464+
n = fmt.format(number)
460465
part1, part2 = n.split("e")
461466
# Normalise exponent: int() strips the "+" sign and leading zeros,
462467
# while preserving "-" and a single "0" for 10⁰.

‎tests/test_number.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,10 @@ def test_fractional(test_input: float | str, expected: str) -> None:
275275
([-(10**400)], "-1.00 x 10⁴⁰⁰"),
276276
([12345 * 10**400, 3], "1.234 x 10⁴⁰⁴"),
277277
([10**400, 0], "1 x 10⁴⁰⁰"),
278+
(["1" + "0" * 400], "1.00 x 10⁴⁰⁰"),
279+
(["-1" + "0" * 400], "-1.00 x 10⁴⁰⁰"),
280+
(["1e400"], "1.00 x 10⁴⁰⁰"),
281+
(["1e-400"], "1.00 x 10⁻⁴⁰⁰"),
278282
([0], "0.00 x 10⁰"),
279283
],
280284
)

0 commit comments

Comments
 (0)