python/cpython · error · OverflowError
cannot round an infinity
Error message
cannot round an infinity
What it means
round(Decimal('Infinity')) — one-argument form — raises OverflowError('cannot round an infinity'); there is no nearest integer to an unbounded value. Mirrors __int__/__trunc__ behavior on infinities.
Source
Thrown at Lib/_pydecimal.py:1846
... round(Decimal('-Infinity'), 37)
... round(Decimal('sNaN123'), 0)
Decimal('NaN')
Decimal('NaN123')
"""
if n is not None:
# two-argument form: use the equivalent quantize call
if not isinstance(n, int):
raise TypeError('Second argument to round should be integral')
exp = _dec_from_triple(0, '1', -n)
return self.quantize(exp)
# one-argument form
if self._is_special:
if self.is_nan():
raise ValueError("cannot round a NaN")
else:
raise OverflowError("cannot round an infinity")
return int(self._rescale(0, ROUND_HALF_EVEN))
def __floor__(self):
"""Return the floor of self, as an integer.
For a finite Decimal instance self, return the greatest
integer n such that n <= self. If self is infinite or a NaN
then a Python exception is raised.
"""
if self._is_special:
if self.is_nan():
raise ValueError("cannot round a NaN")
else:
raise OverflowError("cannot round an infinity")
return int(self._rescale(0, ROUND_FLOOR))
def __ceil__(self):View on GitHub (pinned to bc6749cc3b)
Solutions
- Guard with is_infinite() and render a sentinel like '∞'/'inf' or reject
- Fix the source: enable the Overflow trap or raise Context.prec so infinity never appears
- Clamp to a domain maximum before rounding when a bounded display is acceptable
Example fix
// before shown = round(v) # OverflowError when v is Infinity // after shown = 'inf' if v.is_infinite() else round(v)
Defensive patterns
Strategy: validation
Validate before calling
def safe_round1(d):
if d.is_infinite():
raise OverflowError(f'cannot round {d}')
return round(d) Type guard
def is_roundable(d) -> bool:
return not d._is_special Try / catch
try:
n = round(d)
except OverflowError:
n = display_cap # clamp for display only
except ValueError:
n = 0 # NaN policy Prevention
- Fix overflow at the source: trap Overflow or increase Context.prec
- Guard display/format code against infinities from parsed JSON
- Clamp computed aggregates to domain bounds before rounding
When it happens
Trigger: round(Decimal('Infinity')); round(Decimal('-inf')); values that overflowed to infinity earlier (Overflow trap disabled) then rounded for display.
Common situations: Formatting computed results for report output where an earlier operation overflowed silently; parsing 'Infinity' from JSON (json.loads accepts it) then rounding.
Related errors
- Cannot convert infinity to integer
- Second argument to round should be integral
- cannot round a NaN
- cannot convert Infinity to integer ratio
- timedelta # of days is too large: %d
AI-assisted analysis of python/cpython@bc6749cc3b (2026-08-14).
Data as JSON: /api/errors/4469e8241f7f2d61.
Report an issue: GitHub.