Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions src/humanize/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -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⁰.
Expand Down
9 changes: 9 additions & 0 deletions tests/test_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down