The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Compare floats approximately | same = math.isclose(actual, expected, rel_tol=1e-9, abs_tol=0.0) | View examples |
| Sum floats accurately | total = math.fsum(values) | View examples |
| Inspect an exact float ratio | numerator, denominator = value.as_integer_ratio() | View examples |
| Construct from decimal text | price = Decimal('19.95') | View examples |
| Convert an existing float exactly | value = Decimal.from_float(binary_value) | View examples |
| Set local precision | with localcontext() as ctx: ctx.prec = 12 | View examples |
| Trap inexact arithmetic | ctx.traps[Inexact] = True | View examples |
| Round to a fixed exponent | amount = value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) | View examples |
| Multiply then add once | result = value.fma(multiplier, addend) | View examples |
| Construct an exact fraction | ratio = Fraction(3, 8) | View examples |
| Parse a decimal fraction | ratio = Fraction('0.125') | View examples |
| Approximate with a bounded denominator | ratio = Fraction(value).limit_denominator(1000) | View examples |
| Calculate an arithmetic mean | average = statistics.fmean(values) | View examples |
| Calculate a median | middle = statistics.median(values) | View examples |
| Calculate sample spread | spread = statistics.stdev(values) | View examples |
| Round with Python's built-in policy | rounded = round(value, ndigits) | View examples |
| Format fixed decimal places | text = f'{value:.2f}' | View examples |
Numeric correctness starts by choosing a representation that matches the domain. Binary float is fast and appropriate for most measurement and scientific work, Decimal provides configurable base-10 arithmetic for rules such as monetary rounding, and Fraction preserves exact rational relationships. Comparisons, conversion boundaries, rounding policy, and empty-data behavior should all be explicit.
Step by step
Detailed examples
Treat float as finite binary approximation
Most decimal fractions are not exactly representable as binary float, so equality after arithmetic can be misleading. math.isclose combines relative tolerance with an absolute tolerance that matters near zero. math.fsum is preferable when many values or severe cancellation could amplify ordinary summation error; neither tool defines a domain-specific tolerance for you.
import math
value = 0.1 + 0.2
print(value == 0.3)
print(math.isclose(value, 0.3, rel_tol=1e-12))
print(sum([1e16, 1, -1e16]))
print(math.fsum([1e16, 1, -1e16]))
print((0.5).as_integer_ratio()) False
True
0.0
1.0
(1, 2)Construct Decimal values at a clean boundary
Construct Decimal from strings or integers when the source value is decimal. Passing a float performs its exact binary-to-decimal conversion, often revealing many digits; it does not recover the short decimal text that originally produced the float. Avoid mixing Decimal and float arithmetic, and decide how external JSON or database values enter the decimal boundary.
from decimal import Decimal
from_text = Decimal('0.1')
from_float = Decimal.from_float(0.1)
print(from_text)
print(from_float)
print(from_text * 3 == Decimal('0.3'))
print(Decimal(2) + from_text) 0.1
0.1000000000000000055511151231257827021181583404541015625
True
2.1Localize precision, flags, and traps
A Decimal context controls precision, rounding, exponent limits, flags, and traps for arithmetic. localcontext creates a temporary copy so library code does not silently alter a surrounding calculation. Precision affects operations rather than storage of newly constructed digits. Signals set flags by default, while enabling a trap converts the corresponding condition into an exception.
from decimal import Decimal, Inexact, localcontext
with localcontext() as ctx:
ctx.prec = 5
print(Decimal(1) / Decimal(7))
try:
with localcontext() as ctx:
ctx.traps[Inexact] = True
Decimal(1) / Decimal(3)
except Inexact:
print('inexact trapped')
print(Decimal('1.234567')) 0.14286
inexact trapped
1.234567Quantize at explicit business boundaries
quantize rounds to the exponent of a template Decimal, making scale and policy visible. ROUND_HALF_EVEN reduces aggregate bias and is the default context policy; ROUND_HALF_UP is common in rules that specify ties away from zero. Retain unrounded values during intermediate work when policy allows, then quantize at the stated boundary. fma can avoid one intermediate rounding.
from decimal import Decimal, ROUND_HALF_EVEN, ROUND_HALF_UP
cent = Decimal('0.01')
value = Decimal('2.345')
print(value.quantize(cent, rounding=ROUND_HALF_EVEN))
print(value.quantize(cent, rounding=ROUND_HALF_UP))
subtotal = Decimal('19.99')
print(subtotal.fma(Decimal('0.075'), subtotal).quantize(cent)) 2.34
2.35
21.49Keep ratios exact with Fraction
Fraction stores a normalized numerator and denominator and performs exact rational arithmetic. String construction preserves a written decimal exactly, while float construction preserves the exact binary float ratio. limit_denominator is useful for recovering a simple ratio from a measurement, but its maximum denominator is a modeling choice rather than proof of the original value.
from fractions import Fraction
third = Fraction(1, 3)
eighth = Fraction('0.125')
print(third + eighth)
print(eighth.numerator, eighth.denominator)
print(Fraction(0.333333).limit_denominator(100))
print(float(Fraction(3, 8))) 11/24
1 8
1/3
0.375Select statistics that match the data model
statistics provides calculator-level descriptive functions without a third-party dependency. mean generally preserves compatible numeric types, fmean converts to float, median is robust to extreme values, and stdev computes sample rather than population spread. Empty inputs raise StatisticsError, and mixed numeric types may have undefined or implementation-dependent behavior, so normalize inputs first.
from statistics import fmean, mean, median, stdev
values = [2, 3, 3, 4, 13]
print(mean(values))
print(fmean(values))
print(median(values))
print(round(stdev(values), 3)) 5
5.0
3
4.528Separate stored values from display formatting
round returns a number and follows nearest-even tie breaking, but apparent decimal ties represented as float may already lie slightly above or below the ideal value. Formatting returns text and is the right boundary for a fixed number of displayed digits. Do not parse formatted output back into calculations; use Decimal quantize for contractual decimal rules.
value = 2.675
print(round(value, 2))
print(f'{value:.2f}')
print(round(2.5), round(3.5))
ratio = 1 / 8
print(ratio, f'{ratio:.2%}') 2.67
2.67
2 4
0.125 12.50%Local code tester
Compare numeric representations
Experiment with binary floats, exact decimals, rational values, tolerances, and explicit rounding policies.
Press Run to load Python locally.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
- Python Software FoundationFloating-Point Arithmetic: Issues and Limitationsdocs.python.org
- Python Software Foundationdecimal — Decimal fixed-point and floating-point arithmeticdocs.python.org
- Python Software Foundationfractions — Rational numbersdocs.python.org
- Python Software Foundationmath — Mathematical functionsdocs.python.org
- Python Software Foundationstatistics — Mathematical statistics functionsdocs.python.org
Help us improve
Found a typo or missing example?
Tell us what would make this cheat sheet clearer, more complete, or more useful.



