The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Compare floats approximatelysame = math.isclose(actual, expected, rel_tol=1e-9, abs_tol=0.0)View examples
Sum floats accuratelytotal = math.fsum(values)View examples
Inspect an exact float rationumerator, denominator = value.as_integer_ratio()View examples
Construct from decimal textprice = Decimal('19.95')View examples
Convert an existing float exactlyvalue = Decimal.from_float(binary_value)View examples
Set local precisionwith localcontext() as ctx: ctx.prec = 12View examples
Trap inexact arithmeticctx.traps[Inexact] = TrueView examples
Round to a fixed exponentamount = value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)View examples
Multiply then add onceresult = value.fma(multiplier, addend)View examples
Construct an exact fractionratio = Fraction(3, 8)View examples
Parse a decimal fractionratio = Fraction('0.125')View examples
Approximate with a bounded denominatorratio = Fraction(value).limit_denominator(1000)View examples
Calculate an arithmetic meanaverage = statistics.fmean(values)View examples
Calculate a medianmiddle = statistics.median(values)View examples
Calculate sample spreadspread = statistics.stdev(values)View examples
Round with Python's built-in policyrounded = round(value, ndigits)View examples
Format fixed decimal placestext = 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

01

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.

Compare and sum binary floats deliberately
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())
Output
False
True
0.0
1.0
(1, 2)
Back to quick reference ↑
02

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.

Contrast text and float construction
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)
Output
0.1
0.1000000000000000055511151231257827021181583404541015625
True
2.1
Back to quick reference ↑
03

Localize 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.

Apply temporary precision and trap inexact division
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'))
Output
0.14286
inexact trapped
1.234567
Back to quick reference ↑
04

Quantize 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.

Apply two explicit tie-breaking policies
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))
Output
2.34
2.35
21.49
Back to quick reference ↑
05

Keep 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.

Calculate and approximate rational values
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)))
Output
11/24
1 8
1/3
0.375
Back to quick reference ↑
06

Select 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.

Compare center and sample spread
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))
Output
5
5.0
3
4.528
Back to quick reference ↑
07

Separate 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.

Distinguish numeric rounding from formatting
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%}')
Output
2.67
2.67
2 4
0.125 12.50%
Back to quick reference ↑

Local code tester

Compare numeric representations

Experiment with binary floats, exact decimals, rational values, tolerances, and explicit rounding policies.

Runs in your browser
Output
Press Run to load Python locally.

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. Python Software FoundationFloating-Point Arithmetic: Issues and Limitationsdocs.python.org
  2. Python Software Foundationdecimal — Decimal fixed-point and floating-point arithmeticdocs.python.org
  3. Python Software Foundationfractions — Rational numbersdocs.python.org
  4. Python Software Foundationmath — Mathematical functionsdocs.python.org
  5. 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.

Share feedback