sigfig - Scientific Rounding
sigfig is a Python library (current version 1.3.19) designed for precise rounding of numbers based on significant figures, decimal places, or uncertainty. It also provides versatile formatting options and can interpret various numeric input types (e.g., strings, floats, Decimals). The library aims to provide expected rounding results in scientific and engineering contexts, often differing from Python's built-in `round()` function. It is actively maintained with releases as recent as March 2025.
Common errors
-
UserWarning: warning: X significant figures requested from number with only Y significant figures
cause You are attempting to round a number to more significant figures than it inherently possesses or than `sigfig` can infer from its type. For example, passing the integer `1` and requesting `sigfigs=3`.fixProvide the number with sufficient precision (e.g., as a string `'1.00'`). Alternatively, if the intent is to enforce a minimum number of significant figures, suppress the warning: `from sigfig import round; round(1, sigfigs=3, warn=False)`. -
Incorrect rounding or significant figure count for numbers with trailing zeros (e.g., 10.0, 1200)
cause Python's `float` type often discards trailing zeros that are significant in scientific notation (e.g., `float('10.00')` might be `10.0`). When `sigfig` receives such a float, it loses the original precision information.fixAlways pass numbers as strings (e.g., `'10.00'`, `'1200.'`) or `decimal.Decimal` objects to `sigfig.round()` to preserve all significant digits, including trailing zeros. Example: `from sigfig import round; round('10.00', sigfigs=3)`.
Warnings
- gotcha Python's native float type can lead to precision loss, especially with trailing zeros (e.g., `10.0` might internally be `10.0` with 2 sigfigs, not `10.00` with 3). This can cause `sigfig` to misinterpret the intended precision.
- gotcha Importing `from sigfig import round` directly overwrites the built-in `round()` function. This can lead to unexpected behavior if other parts of your code rely on the standard `round()` behavior.
- gotcha The library may issue a `UserWarning` if you request more significant figures than the input number inherently possesses, indicating potential 'invented numbers'.
Install
-
pip install sigfig
Imports
- round
round(0.25, 1)
from sigfig import round
Quickstart
from sigfig import round
# Round to 4 significant figures
result_sigfigs = round('123.456', sigfigs=4)
print(f"Rounded to significant figures: {result_sigfigs}")
# Round to 2 decimal places
result_decimals = round('3.14159', decimals=2)
print(f"Rounded to decimal places: {result_decimals}")
# Round by uncertainty
result_uncertainty = round('3.14159', uncertainty=2)
print(f"Rounded by uncertainty: {result_uncertainty}")