Parse a string as an integer or float in Python

Use int or float with explicit error handling, reject non-finite values when required, and avoid losing precision through unnecessary float conversion.

Best practices
Python programming and application logging

Use int(text) for an integer and float(text) for a floating-point number. Invalid numeric strings raise ValueError; values of an unsupported input type can raise TypeError.

print(int("42"))       # 42
print(float("3.14"))   # 3.14
print(float("42"))     # 42.0
print(int("  42  "))  # 42

Choose a fallback policy

If your interface deliberately accepts strings only and permits either numeric type:

import math

def to_number(text, default=None):
    if not isinstance(text, str):
        return default
    try:
        return int(text)
    except ValueError:
        try:
            value = float(text)
        except ValueError:
            return default
        return value if math.isfinite(value) else default

print(to_number("42"))    # 42
print(to_number("3.14"))  # 3.14
print(to_number("abc"))   # None
print(to_number("nan"))   # None

Using None by default keeps failed parsing distinct from a real zero. A stricter API may raise an error instead. float() accepts infinities and NaN; this example rejects them because it requires a finite result. It is still a binary float parser, not an exact decimal validator.

Watch decimal and formatting boundaries

int("3.14") raises ValueError. int(float("3.14")) returns 3, truncating toward zero, but converting through float can lose precision for large integers or decimal inputs. Use Decimal when the intended rule is exact decimal conversion.

Units such as "42px" and thousands separators such as "1,000" are not accepted directly. Removing commas can handle a known validated comma-grouped format, but blindly removing them also accepts malformed grouping and misreads locales where commas are decimal separators. Define the input format first.

Parse another base

print(int("ff", 16))      # 255
print(int("0b101", 2))    # 5
print(int("777", 8))      # 511
print(int("0x10", 0))     # 16; infer a recognized base prefix

With an explicit base, digits must be valid for that base. Python's accepted syntax also includes some Unicode decimal digits and underscores, so add a format check if your interface allows only a narrower ASCII representation.

FAQ

Should I check isdigit first? It does not describe exactly what int() accepts: signs and whitespace can be valid for int, while some characters accepted by isdigit() cannot be parsed as decimal integers. isnumeric() is broader still. Use conversion and handle errors, with separate validation for a restricted format.

Can I parse scientific notation? float("1e5") works; int("1e5") does not. A float can still overflow to infinity, which the finite check above rejects.

How do I retain exact decimal input? Construct Decimal from the original string, choose a precision and rounding policy for later operations, and handle its invalid-input exceptions separately.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting