diff --git a/src/humanize/number.py b/src/humanize/number.py index 52a5356a..e9b672fd 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -442,15 +442,26 @@ def scientific(value: NumberOrString, precision: int = 2) -> str: str: Number in scientific notation z.wq x 10ⁿ. """ import math + from decimal import Decimal + fmt = f"{{:.{int(precision)}e}}" try: - value = float(value) - if not math.isfinite(value): - return _format_not_finite(value) + number = float(value) + except OverflowError: + # An integer beyond float's range: Decimal has no such limit. + n = fmt.format(Decimal(value)) except (ValueError, TypeError): return str(value) - fmt = f"{{:.{int(precision)}e}}" - n = fmt.format(value) + else: + out_of_range = number == 0 or not math.isfinite(number) + exact = Decimal(value) if isinstance(value, str) and out_of_range else None + if exact is not None and exact.is_finite() and exact != 0: + # float() turns a string beyond its range into infinity or zero. + n = fmt.format(exact) + elif not math.isfinite(number): + return _format_not_finite(number) + else: + n = fmt.format(number) part1, part2 = n.split("e") # Normalise exponent: int() strips the "+" sign and leading zeros, # while preserving "-" and a single "0" for 10⁰. diff --git a/tests/test_number.py b/tests/test_number.py index 5fb12fa6..a67327ac 100644 --- a/tests/test_number.py +++ b/tests/test_number.py @@ -271,6 +271,15 @@ def test_fractional(test_input: float | str, expected: str) -> None: ([-math.inf], "-Inf"), (["nan"], "NaN"), (["-inf"], "-Inf"), + ([10**400], "1.00 x 10⁴⁰⁰"), + ([-(10**400)], "-1.00 x 10⁴⁰⁰"), + ([12345 * 10**400, 3], "1.234 x 10⁴⁰⁴"), + ([10**400, 0], "1 x 10⁴⁰⁰"), + (["1" + "0" * 400], "1.00 x 10⁴⁰⁰"), + (["-1" + "0" * 400], "-1.00 x 10⁴⁰⁰"), + (["1e400"], "1.00 x 10⁴⁰⁰"), + (["1e-400"], "1.00 x 10⁻⁴⁰⁰"), + ([0], "0.00 x 10⁰"), ], ) def test_scientific(test_args: list[typing.Any], expected: str) -> None: