Lesson · Date, Time & Numbers
Decimal & Fractions
55 min readDecimal & Fractions
`Decimal` provides configurable base-10 arithmetic and `Fraction` provides exact rational arithmetic. Choose them when the numeric model matters more than the speed and convenience of binary floating point.
Learning goals
- Build a
Decimalfrom a string and round it to a chosen number of places withquantize, naming the rounding rule you passed. - Explain what the decimal context controls and why
Decimal("0.1")andDecimal(0.1)store different values. - Add
Fractionvalues exactly and point to where numerator and denominator grow as operations accumulate. - Choose between
float,DecimalandFractionfor a money or measurement task, justifying the choice from the model's guarantees. - Reproduce the binary-float error in
0.1 + 0.2and show howDecimalandFractionavoid it.
Mental model
Python offers three numeric models, and the lesson is about choosing between them. Binary float is the fast default, but values like 0.1 have no exact base-2 representation, so small errors accumulate when they are summed. Decimal stores base-10 digits under a context that fixes precision and rounding, which is what money and prices need. Fraction keeps an exact numerator and denominator, so ratios never approximate at all, at the cost of numbers that can grow as operations accumulate.
Core idea
Every numeric type is a model with a public contract: which values it represents exactly, how it rounds, and what its arithmetic guarantees. The lesson's organizing move is to pick the model from the domain's requirements: money needs base-10 digits and a deliberate rounding rule, so Decimal; ratios need exactness, so Fraction; speed and abstract measurements usually accept binary approximation, so float. Python does not blend the models for you, so a mismatch like Decimal("0.1") + 0.1 raises TypeError instead of quietly converting one side.
Decimal
Decimal represents decimal floating-point with configurable precision and rounding. Construct from strings when exact decimal input matters, because constructing from a binary float preserves its binary approximation.
Decimal context
The decimal context is the rule set that Decimal arithmetic follows: precision (how many significant digits results keep), rounding mode (half-even by default), and which conditions raise errors such as InvalidOperation or DivisionByZero. getcontext() shows the active context and localcontext() applies temporary settings for one block. The context is inherited rather than passed per operation, so the same expression can produce different results under different contexts, and quantize's rounding= argument overrides it only for that call.
Financial arithmetic
Financial rules often require decimal input, defined precision, and explicit rounding. Decimal supports these policies more directly than binary floating point.
Fraction
Fraction represents exact rational numbers as numerator and denominator. It is valuable for exact ratios, but arithmetic can grow numerator and denominator sizes.
Exact rational arithmetic
Exact rational arithmetic keeps every result as an integer ratio instead of rounding it: Fraction(2, 3) + Fraction(1, 6) is exactly Fraction(5, 6), and comparisons such as Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10) are reliable. The trade-off is growth: numerators and denominators can become much larger as operations accumulate, where a binary float would round back to a fixed size.
Walkthrough
Decimal("19.995")builds the value from the string's digits; the quotes matter, becauseDecimal(19.995)would instead capture the binary float's approximation of 19.995.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)rounds to the number of decimal places in0.01, which is two, and applies half-up rounding, so the printed result is20.00. Droprounding=and the call follows the context's default, which is half-even.Fraction(2, 3) + Fraction(1, 6)adds the ratios exactly: the result isFraction(5, 6), and nothing was rounded becauseFractionstores a numerator and a denominator rather than a binary approximation.- Predict before running: what the two
printcalls show, whetherpricekeeps three decimal places or two, and whetherratioprints as a numerator and denominator or as a decimal number.
Experiments to try
- Print
0.1 + 0.2,Decimal("0.1") + Decimal("0.2")andFraction(1, 10) + Fraction(2, 10), then compare each result against the exact valueFraction(3, 10); record which comparisons areTrue. - Print
Decimal(19.99)andDecimal("19.99")side by side and find where the digits first diverge; then repeat the experiment withFraction(0.1)andFraction("0.1"). - Run the quantize line three times with
rounding=ROUND_DOWN,ROUND_HALF_EVENandROUND_HALF_UPonDecimal("19.985"); list which modes give19.98and which give19.99. - Use
localcontext()to set precision 4 and computeDecimal(1) / Decimal(3)inside and outside the block; compare how many digits each result keeps.
Common mistakes
- Building a
Decimalfrom a float:Decimal(0.1)stores the float's full binary expansion (55 digits) rather than one tenth, because the constructor converts the float exactly. Pass a string,Decimal("0.1"), whenever the decimal digits are the intent. - Mixing the models in one expression:
Decimal("0.1") + 0.1raisesTypeErrorbecause Python refuses to guess which side should convert. Choose the model at the boundary, for exampleDecimal(str(value))for input that arrives as a float. - Writing
Fraction(0.1)and expecting1/10: the constructor converts the float exactly, so the result is3602879701896397/36028797018963968; useFraction(1, 10)orFraction("0.1")instead. - Assuming
quantize(rounding=...)configures rounding everywhere: it applies to that call only, while+,-,*and/follow the active context (precision 28, half-even by default), so results can round where you did not look.
Practice: Easy
- Run the worked example, then print
ratio.numeratorandratio.denominator; check both withtype(...)and state what each holds. - Build
Decimal("19.99")andDecimal(19.99)and print both; point to the first digit where they differ from what a price of 19.99 should be. - Compare
0.1 + 0.2with0.3using==, then compareDecimal("0.1") + Decimal("0.2")withDecimal("0.3"); report both results and explain the difference.
Practice: Medium
- Write
total(price_texts)that converts each string withDecimal(text), adds the values, and returns the sum quantized toDecimal("0.01")withROUND_HALF_UP; test it on the worked example's19.995plus0.01. - Write
as_decimal(fraction, places)that converts aFractionto aDecimalby dividing its numerator and denominator, quantized to the given number of places withROUND_HALF_UP; test it withFraction(2, 3)at 6 places. - Add one tenth to itself ten times, once with floats and once with
Decimal("0.1")values; compare both totals with1and explain which model lost the value.
Practice: Hard
- Design
split_bill(total, people)that returns each person's share as aDecimalquantized to0.01plus the rounding remainder, and define who absorbs the leftover part when the cents do not divide evenly. - Failure lab: trigger the
TypeErrorfromDecimal("0.1") + 0.1, theInvalidOperationfromDecimal("abc"), and the long fraction fromFraction(0.1); for each error, state what it shows about the model being used. - Connect this lesson to the data formats module: JSON numbers arrive as floats, so describe the round trip a price needs when it is stored as JSON and loaded back as money, including the conversion that recovers clean decimal digits and the precision that may already be lost.
Lesson checklist
- I can build a
Decimalfrom a string and say why the string constructor preserves the digits I typed. - I can round a value with
quantizeand name the rounding rule I passed. - I can keep a ratio exact with
Fractionand point to where its numerator and denominator can grow. - I can choose among
float,DecimalandFractionfrom the guarantees a task needs, and explain whyDecimal("0.1") + 0.1raises instead of converting.
Remember
`Decimal` and `Fraction` exist because binary `float` cannot represent most decimal fractions or exact ratios, and for prices and exact math that difference is the bug. `Decimal` keeps base-10 digits under a context that fixes precision and rounding; `Fraction` keeps an exact numerator and denominator, at the cost of growing them. Choose by the guarantee the domain needs: a deliberate rounding rule for money, exactness for ratios, speed for everything that tolerates approximation.
Interview angles
What is the main purpose of **Decimal**?+
Decimal represents decimal floating-point with configurable precision and rounding. Construct from strings when exact decimal input matters, because constructing from a binary float preserves its binary approximation.
What should you pay attention to when using **Decimal context**?+
The context fixes precision, rounding mode and error traps for all Decimal arithmetic in the current thread, with precision 28 and half-even rounding by default. quantize(rounding=...) overrides the mode for that one call, and localcontext() changes the rules for a block, so check the context whenever exact rounding matters.
How does **Financial arithmetic** fit into this lesson?+
Financial rules often require decimal input, defined precision, and explicit rounding. Decimal supports these policies more directly than binary floating point.
Why does `Decimal(0.1)` print far more digits than `Decimal("0.1")`?+
Decimal(0.1) converts the float exactly, and 0.1 has no exact binary representation, so the constructor stores the float's full approximation (55 digits). Decimal("0.1") parses the decimal digits directly and stores exactly one tenth. Pass a string whenever the printed digits are the intent.