fastnumbers: Super-fast and clean conversions to numbers

5.1.1 · active · verified Thu Apr 16

fastnumbers is a Python C extension designed for super-fast and clean conversions of strings and other types to numbers. It provides convenient error handling, functions to check if an input can be converted, and drop-in replacements for built-in `int` and `float` that are often faster. The library is actively maintained, with version 5.1.1 being the latest stable release, and typically follows a regular release cadence as needed for bug fixes and improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core functionality of `fastnumbers` using `try_float` and `try_int` for robust number conversions. It shows how to handle unconvertible inputs by returning the original input (default), a specified default value, raising a `ValueError`, or executing a custom callback function.

from fastnumbers import try_float, try_int, RAISE, INPUT

# Basic conversion with default error handling (returns input on failure)
print(f"'123.45' -> {try_float('123.45')}")
print(f"'abc' -> {try_float('abc')}")

# Convert to float, returning a default value on failure
print(f"'abc' with default=0.0 -> {try_float('abc', default=0.0)}")

# Convert to int, raising an error on failure
try:
    print(f"'123' -> {try_int('123')}")
    print(f"'45.67' -> {try_int('45.67')}") # Truncates float strings to int
    print(f"'xyz' -> {try_int('xyz', on_fail=RAISE)}")
except ValueError as e:
    print(f"'xyz' with on_fail=RAISE -> {e}")

# Convert to float, using a custom function on failure
def handle_fail(val):
    return f"Failed to convert: {val}"
print(f"'bad_num' with custom handler -> {try_float('bad_num', on_fail=handle_fail)}")

view raw JSON →