Course outline

Python / Foundations / Lesson 7

Decimal values and explicit rounding

Represent decimal input and rounding policies with Python Decimal.

About 19 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Distinguish decimal intent from binary approximation.
  • Apply and test an explicit rounding rule.
  • Construct decimal values from text and distinguish numeric equality from representation scale.
  • Apply an explicit rounding mode and stage to synthetic decimal calculations.

Binary approximation and decimal meaning

Some decimal fractions cannot be represented exactly as finite binary floating-point values. A float is useful for many measurements, but its displayed decimal form can hide the stored approximation. For example, repeated arithmetic may produce a result close to an expected decimal rather than exactly equal to it. Before choosing a numeric type, decide whether the domain needs exact decimal input, approximate measurement, or rational arithmetic. The representation does not by itself define how a business rule rounds a result. Keep that policy explicit and test boundaries where a choice of rounding changes the answer.

Construct from decimal text

Decimal accepts a decimal string, preserving the intended digits at construction. The following example uses a string for the unit price and for the expected total, so three tenths compares equal to thirty hundredths. Constructing Decimal from an existing float instead preserves the exact value of that binary float, including its approximation; it does not recover the original human decimal intention. At an input boundary, validate the supplied text and handle invalid input deliberately. Avoid silently treating malformed or missing amounts as zero, because that would turn an input failure into a plausible but incorrect total.

python Decimal input and equality
from decimal import Decimal

price = Decimal("0.10")
total = price * 3
print(total)
print(total == Decimal("0.30"))
Expected output
0.30
True

The decimal strings express the intended quantities without first converting through a binary float.

Specify rounding deliberately

A decimal representation still needs a rule for operations that produce more digits than the output permits. quantize rounds to the exponent of its argument; here Decimal("0.01") expresses two decimal places and ROUND_HALF_UP states the chosen tie rule. The example makes one local choice, not a universal rule for currency. A real application must obtain its rounding mode and rounding point from its domain requirements. Rounding each item before summing can differ from rounding the final sum, so document the required order and check a boundary case such as a value ending in five.

python An explicit rounding rule
from decimal import Decimal, ROUND_HALF_UP

amount = Decimal("1.235")
cents = amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print(cents)
Expected output
1.24

The result uses the explicitly named rule at two decimal places.

Separate calculation and display

Formatting controls the text shown to a reader; it does not necessarily change the value held by the program. Conversely, quantizing creates a rounded Decimal result that can be used by later calculations. Decide whether a rounded value is only a display view or a value recorded by the domain, and avoid repeated rounding at unrelated layers. Include the unit and scale in the contract: an amount in cents is not interchangeable with an amount in whole units. A test should check both the internal calculation and the formatted output when each is part of the requirement.

Check assumptions with examples

Start with a small table of inputs, expected values, and the reason for each result. Include zero, a negative value if the domain permits it, a tie at the rounding boundary, and malformed input. Compare decimal values as decimals and approximate measurements with a domain-appropriate tolerance rather than an arbitrary tolerance chosen merely to make a test pass. Decimal arithmetic is also governed by a context with precision and rounding settings, so do not assume every operation has unlimited precision. If the policy depends on the context, make it explicit and test it in isolation.

Preserve the intended decimal input

Decimal represents decimal numbers using a sign, coefficient, and exponent. Constructing Decimal from a string such as "0.20" preserves the exact decimal value and its exponent, so its display can retain two fractional places. Constructing from a binary float instead captures the floatโ€™s exact binary approximation as a decimal value, which is usually not what a human-entered decimal amount intended. Parse a documented decimal text field directly and validate it before using it in a calculation.

The exponent and displayed trailing zeros can communicate a chosen scale, but they do not by themselves define a currency, a tax rule, or an acceptable input range. Decimal("1.0") and Decimal("1.00") compare numerically equal even though their representations have different exponents. Decide separately whether the application requires a particular scale for storage or display. Keep a currency or unit alongside a monetary amount in real records and reject invalid or incompatible inputs at the boundary.

Specify rounding and the target exponent

quantize returns a Decimal rounded to the exponent of its second operand, subject to the supplied rounding mode and context. Decimal("0.01") expresses two fractional places; Decimal("1") expresses a whole-unit exponent. The digits of the quantizer are not a general increment rule: quantizing to Decimal("0.05") selects the same exponent as cents and does not by itself round to the nearest five cents. A five-cent rule needs an explicitly designed division, integral rounding, multiplication, and appropriate validation.

ROUND_HALF_UP sends an exact tie away from zero, whereas ROUND_HALF_EVEN selects the result whose last retained digit is even at an exact tie. For 2.345 quantized to cents, these produce 2.35 and 2.34 respectively. Negative ties must also be tested: half up sends -2.345 to -2.35. Name the mode in the contract rather than relying on an unstated default. Values immediately below and above the tie are useful tests as well as the tie itself.

Choose where rounding occurs

The stage at which rounding happens affects a total. Rounding each line item and adding can differ from adding unrounded amounts and rounding once. Neither is universally correct; a contractual or regulatory rule determines the required stage. Record the unrounded inputs, the rate, the chosen scale, the mode, and the stage so another person can reproduce the result. Use synthetic values when testing and do not infer a real tax policy from a demonstration.

For example, with two synthetic amounts of 0.005, half-up rounding each to cents produces 0.01 plus 0.01, or 0.02. Adding first gives 0.010, which quantizes to 0.01. Both calculations follow their stated rules; the difference arises from the stage. Test repeated small values, negative adjustments, and exact boundaries before implementing a policy. If intermediate values must remain unrounded, avoid an earlier display-formatting step becoming an accidental calculation input.

Understand context and invalid input

Decimal operations use a context that includes precision, rounding, and signals. Precision is the number of significant digits for arithmetic, not the number of digits after the decimal point. Quantize controls the result exponent, and it can signal InvalidOperation if the result cannot fit the active precision. localcontext creates a temporary context so a demonstration or calculation can adjust precision without silently changing unrelated calculations outside its block.

Malformed decimal text can raise InvalidOperation under the usual context. Decide how an application reports invalid input, rather than treating it as zero or exposing unrelated record contents. Special values such as NaN and Infinity exist, so a financial-style contract that requires finite amounts should explicitly check is_finite before applying range or rounding rules. Never assume that successful construction alone establishes a valid domain amount.

Verify representation, arithmetic, and boundaries

Build tests around a documented contract: valid decimal text, intended scale, finite-value requirement, rounding mode, and rounding stage. Include an exact tie, a value on either side of it, a negative tie, zero, and a malformed value. Check the returned Decimal and its exponent when scale matters; comparing numeric equality alone cannot distinguish 1.0 from 1.00. Also check that temporary context changes do not escape their intended scope.

Use a fixed synthetic fixture and calculate expected results independently before running the program. Compare the exact displayed result as well as the numerical value when trailing zeros are required. The examples below are self-contained standard-library Python programs, verified in fresh local processes. They demonstrate mathematical policies rather than asserting that one rounding rule applies to every currency or business. A production system must choose and document its own units and rules.

20 worked examples

1. Multiply decimal text

Problem: Multiply the synthetic decimal amount 0.20 by three and inspect the displayed result.

  1. The string constructor represents the decimal input exactly with two fractional places.
  2. Multiplying by three produces 0.60 in this calculation.
python Multiply decimal text
from decimal import Decimal
x = Decimal("0.20")
print(x * 3)
Expected output
0.60

Why this result follows: Constructing from text avoids importing a binary float approximation into the decimal value.

2. Numeric equality and scale

Problem: Compare two decimals that have equal numerical value but different written scales.

  1. Both values represent the number one.
  2. Their stored exponents differ, but the numeric equality comparison still returns True.
python Numeric equality and scale
from decimal import Decimal
print(Decimal("1.0") == Decimal("1.00"))
Expected output
True

Why this result follows: Decimal equality compares numerical values rather than requiring identical representations of trailing zeros.

3. Inspect decimal exponent

Problem: Find the stored exponent for two numerically equal decimal values.

  1. The first value has one fractional digit, so its exponent is negative one.
  2. The second has two fractional digits and exponent negative two.
python Inspect decimal exponent
from decimal import Decimal
a = Decimal("1.0")
b = Decimal("1.00")
print(a.as_tuple().exponent, b.as_tuple().exponent)
Expected output
-1 -2

Why this result follows: The representation retains an exponent that can distinguish the specified decimal scales.

4. Round a positive tie half up

Problem: Round the exact decimal tie 2.345 to cents using the specified half-up rule.

  1. The discarded digit is five at an exact halfway point between 2.34 and 2.35.
  2. Half up chooses 2.35, away from zero at this positive tie.
python Round a positive tie half up
from decimal import Decimal, ROUND_HALF_UP
print(Decimal("2.345").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
Expected output
2.35

Why this result follows: quantize applies the supplied rounding mode at the exponent of the cents operand.

5. Round a tie half even

Problem: Round the same exact decimal tie to cents using half-even rounding.

  1. The adjacent cent values are 2.34 and 2.35.
  2. The retained hundredths digit of 2.34 is even, so half even selects it.
python Round a tie half even
from decimal import Decimal, ROUND_HALF_EVEN
print(Decimal("2.345").quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN))
Expected output
2.34

Why this result follows: Half-even rounding chooses the even last retained digit when the value is exactly halfway.

6. Round a negative tie

Problem: Apply half-up rounding to a negative decimal tie at the cent boundary.

  1. The value lies halfway between -2.34 and -2.35.
  2. Half up moves away from zero at this tie and produces -2.35.
python Round a negative tie
from decimal import Decimal, ROUND_HALF_UP
print(Decimal("-2.345").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
Expected output
-2.35

Why this result follows: The specified half-up mode handles the sign consistently at an exact halfway value.

7. Round below a tie

Problem: Round a decimal just below the halfway point to two fractional places.

  1. The value 2.344 is closer to 2.34 than to 2.35.
  2. Quantizing to the cents exponent returns 2.34.
python Round below a tie
from decimal import Decimal, ROUND_HALF_UP
print(Decimal("2.344").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
Expected output
2.34

Why this result follows: A value below the halfway boundary rounds to the nearer lower cent in this case.

8. Round above a tie

Problem: Round a decimal just above the halfway point to two fractional places.

  1. The value 2.346 is closer to 2.35 than to 2.34.
  2. The specified quantization therefore produces 2.35.
python Round above a tie
from decimal import Decimal, ROUND_HALF_UP
print(Decimal("2.346").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
Expected output
2.35

Why this result follows: A value above the halfway boundary rounds to the nearer upper cent in this case.

9. Round toward zero

Problem: Quantize a negative decimal to cents using the explicitly selected ROUND_DOWN mode.

  1. The discarded thousandths digit is nine.
  2. ROUND_DOWN moves toward zero, producing -1.23 rather than the more negative -1.24.
python Round toward zero
from decimal import Decimal, ROUND_DOWN
print(Decimal("-1.239").quantize(Decimal("0.01"), rounding=ROUND_DOWN))
Expected output
-1.23

Why this result follows: The named mode determines direction; down here means toward zero rather than negative infinity.

10. Round toward negative infinity

Problem: Quantize the same negative amount using the floor rounding mode.

  1. The original value lies between -1.23 and -1.24.
  2. ROUND_FLOOR chooses the value toward negative infinity, -1.24.
python Round toward negative infinity
from decimal import Decimal, ROUND_FLOOR
print(Decimal("-1.239").quantize(Decimal("0.01"), rounding=ROUND_FLOOR))
Expected output
-1.24

Why this result follows: For a negative value, rounding toward negative infinity differs from rounding toward zero.

11. Round to a whole unit

Problem: Round an exact halfway value to a whole unit using half up.

  1. The quantizer Decimal("1") specifies exponent zero.
  2. The tie at 2.5 rounds away from zero to three.
python Round to a whole unit
from decimal import Decimal, ROUND_HALF_UP
print(Decimal("2.5").quantize(Decimal("1"), rounding=ROUND_HALF_UP))
Expected output
3

Why this result follows: The quantizer exponent selects whole units while the explicit mode resolves the tie.

12. A quantizer is not an increment

Problem: Check whether quantizing 1.234 to 0.05 alone selects a multiple of five cents.

  1. Decimal("0.05") has exponent negative two, the same scale as cents.
  2. Quantize returns 1.23, which is not a multiple of 0.05.
python A quantizer is not an increment
from decimal import Decimal
print(Decimal("1.234").quantize(Decimal("0.05")))
Expected output
1.23

Why this result follows: quantize matches the operand exponent rather than automatically rounding to its numeric increment.

13. Round to a five-cent increment

Problem: Apply a synthetic nearest-five-cent rule to 1.23 using half-up integral rounding.

  1. Dividing by 0.05 gives 24.6 increments, which rounds to 25.
  2. Multiplying 25 by 0.05 gives 1.25.
python Round to a five-cent increment
from decimal import Decimal, ROUND_HALF_UP
x = Decimal("1.23")
step = Decimal("0.05")
print((x / step).quantize(Decimal("1"), rounding=ROUND_HALF_UP) * step)
Expected output
1.25

Why this result follows: Scaling to increment units before rounding implements this explicit nearest-increment policy for the amount.

14. Round each item first

Problem: Compute a synthetic total after rounding each of two half-cent items separately.

  1. Each 0.005 rounds half up to 0.01 at the cent scale.
  2. Adding the two rounded item values gives 0.02.
python Round each item first
from decimal import Decimal, ROUND_HALF_UP
cent = Decimal("0.01")
items = [Decimal("0.005"), Decimal("0.005")]
print(sum(x.quantize(cent, rounding=ROUND_HALF_UP) for x in items))
Expected output
0.02

Why this result follows: Rounding each line before addition applies the chosen policy independently to both lines.

15. Round only the total

Problem: Compute the same synthetic items by summing first and rounding once.

  1. The exact decimal sum is 0.010 before rounding.
  2. Quantizing that exact total to the cents exponent yields the result 0.01.
python Round only the total
from decimal import Decimal, ROUND_HALF_UP
items = [Decimal("0.005"), Decimal("0.005")]
print(sum(items).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
Expected output
0.01

Why this result follows: Deferring rounding until after addition can produce a different result from line-by-line rounding.

16. Limit significant digits

Problem: Calculate one seventh in a local context with three significant digits.

  1. The quotient has a repeating decimal expansion.
  2. The local precision limits the arithmetic result to three significant digits, displayed as 0.143.
python Limit significant digits
from decimal import Decimal, localcontext
with localcontext() as ctx:
    ctx.prec = 3
    print(Decimal("1") / Decimal("7"))
Expected output
0.143

Why this result follows: Context precision controls significant arithmetic digits rather than a fixed number of fractional places.

17. Reject malformed decimal text

Problem: Handle a synthetic decimal input that cannot be parsed as a decimal number.

  1. The input text is not a valid Decimal literal.
  2. Construction raises InvalidOperation and the handler prints the diagnostic.
python Reject malformed decimal text
from decimal import Decimal, InvalidOperation
try:
    Decimal("not-a-number")
except InvalidOperation:
    print("invalid amount")
Expected output
invalid amount

Why this result follows: The input boundary can report invalid syntax rather than silently substituting a numeric value.

18. Check finite amounts

Problem: Distinguish an ordinary synthetic amount from an infinite decimal special value.

  1. 12.50 is a finite decimal value.
  2. Infinity is a supported special value but is not finite.
python Check finite amounts
from decimal import Decimal
print(Decimal("12.50").is_finite(), Decimal("Infinity").is_finite())
Expected output
True False

Why this result follows: A domain requiring finite amounts must check that requirement separately from construction.

19. Avoid constructing from a float

Problem: Compare decimal text input with a decimal constructed from the binary float 0.1.

  1. The text constructor creates exactly one tenth.
  2. The float constructor captures the binary float approximation, which is not exactly one tenth.
python Avoid constructing from a float
from decimal import Decimal
a = Decimal("0.1")
b = Decimal(0.1)
print(a == b)
Expected output
False

Why this result follows: Constructing from a float preserves its approximation rather than recovering the original decimal spelling.

20. Represent zero at cent scale

Problem: Quantize an exact zero to two fractional places using an explicit mode.

  1. The quantizer specifies exponent negative two.
  2. The resulting zero is displayed as 0.00 at the requested scale.
python Represent zero at cent scale
from decimal import Decimal, ROUND_HALF_UP
value = Decimal("0")
print(value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
Expected output
0.00

Why this result follows: quantize sets the result exponent even when the numerical value is zero.

Common errors and fixes

Unexpected decimal digits

Why it happens
A binary float was converted into Decimal.
How to fix it
Construct from validated decimal text.
Prevent it next time
Keep input text until decimal parsing.

A rounded total differs from the expected total

Why it happens
Rounding was applied at a different point.
How to fix it
Implement the specified order and rule.
Prevent it next time
Document and test boundary examples.

A displayed amount differs from later calculations

Why it happens
Formatting changed text but not the stored value.
How to fix it
Quantize the value when the domain requires it.
Prevent it next time
Separate display formatting from recorded rounding.

20 practice exercises

1. Calculate Decimal("0.20") multiplied by three and explain the result.

Show hint

Construct the amount from text and multiply the decimal value by three.

Show worked solution

The result is Decimal("0.60"). The string gives an exact decimal input, and multiplication by three retains the two fractional places in this example.

Decimal("0.20") represents the input decimal exactly. Multiplication by three produces Decimal("0.60"), displayed as 0.60 in this example. The two fractional places in the representation remain visible.

Check your solution

  • The numerical product is six tenths
  • The displayed result is 0.60

2. Round Decimal("2.345") to cents with ROUND_HALF_UP.

Show hint

Quantize to Decimal("0.01") with ROUND_HALF_UP specified explicitly.

Show worked solution

Quantizing with Decimal("0.01") and ROUND_HALF_UP yields Decimal("2.35"). State this rule explicitly because another tie policy can give a different answer.

The value 2.345 is exactly halfway between 2.34 and 2.35. ROUND_HALF_UP selects 2.35 at this positive tie. Another tie policy can select a different result, so record the chosen rule.

Check your solution

  • The target exponent is -2
  • The half-up result is 2.35

3. Multiply Decimal("0.30") by four and state the exact displayed decimal result. Explain the result and the stated rounding rule.

Show hint

Construct the input from its decimal text.

Show worked solution

Decimal("0.30") * 4 yields Decimal("1.20"), displayed as 1.20. The string preserves the intended decimal input, and the multiplication retains two fractional places in this example. Check the exact value and the stated rounding policy.

Check your solution

  • The displayed result is 1.20
  • The decimal input is constructed from text

4. Compare Decimal("2.0") and Decimal("2.00") for numeric equality and explain their scales. Explain the result and the stated rounding rule.

Show hint

Compare numerical value separately from the stored exponent.

Show worked solution

The values compare equal because both represent two. Their exponents are -1 and -2 respectively, so their written scales differ. Numeric equality alone does not verify a required representation scale.

Check your solution

  • Numeric equality is True
  • The exponents are -1 and -2

5. Round Decimal("4.565") to cents using ROUND_HALF_UP and explain the tie. Explain the result and the stated rounding rule.

Show hint

The quantizer Decimal("0.01") sets the cent exponent.

Show worked solution

The value is exactly halfway between 4.56 and 4.57. ROUND_HALF_UP selects 4.57, away from zero at this positive tie. Pass the mode explicitly to quantize. Check the exact value and the stated rounding policy.

Check your solution

  • The result is 4.57
  • The selected mode is ROUND_HALF_UP

6. Round Decimal("4.565") to cents using ROUND_HALF_EVEN and explain the selected digit. Explain the result and the stated rounding rule.

Show hint

At an exact tie select the even last retained digit.

Show worked solution

The neighboring cent values are 4.56 and 4.57. The hundredths digit of 4.56 is even, so ROUND_HALF_EVEN yields 4.56. The mode differs from half up for this tie. Check the exact value and the stated rounding policy.

Check your solution

  • The result is 4.56
  • The retained hundredths digit is even

7. Round Decimal("-4.565") to cents using ROUND_HALF_UP and state the direction at the tie.

Show hint

Half up moves away from zero at an exact tie.

Show worked solution

The negative value lies halfway between -4.56 and -4.57. ROUND_HALF_UP gives -4.57, away from zero. Test negative ties explicitly because their direction can be easy to misread. Check the exact value and the stated rounding policy.

Check your solution

  • The result is -4.57
  • The tie moves away from zero

8. Round Decimal("3.214") and Decimal("3.216") to cents with ROUND_HALF_UP. Explain the result and the stated rounding rule.

Show hint

Compare each value with the midpoint 3.215.

Show worked solution

3.214 lies below the midpoint and rounds to 3.21. 3.216 lies above the midpoint and rounds to 3.22. These cases verify both sides of the boundary independently. Check the exact value and the stated rounding policy.

Check your solution

  • The first result is 3.21
  • The second result is 3.22

9. Quantize Decimal("-2.789") to cents with ROUND_DOWN and explain the direction. Explain the result and the stated rounding rule.

Show hint

ROUND_DOWN means toward zero.

Show worked solution

The result is -2.78 because ROUND_DOWN discards the remaining digits toward zero. It does not mean toward negative infinity; that alternative would produce a different value for this negative input.

Check your solution

  • The result is -2.78
  • The direction is toward zero

10. Quantize Decimal("-2.789") to cents with ROUND_FLOOR and compare its direction with zero.

Show hint

Floor moves toward negative infinity.

Show worked solution

The result is -2.79. ROUND_FLOOR chooses the cent value toward negative infinity, farther from zero for this negative input. This differs from ROUND_DOWN, which would yield -2.78. Check the exact value and the stated rounding policy.

Check your solution

  • The result is -2.79
  • The direction is toward negative infinity

11. Round Decimal("5.5") to a whole unit using ROUND_HALF_UP and state the quantizer.

Show hint

Use Decimal("1") to specify exponent zero.

Show worked solution

Quantize with Decimal("1") and ROUND_HALF_UP. The exact tie 5.5 becomes 6. The quantizer sets the whole-unit scale and the rounding mode determines the tie decision. Check the exact value and the stated rounding policy.

Check your solution

  • The result is 6
  • The quantizer has exponent zero

12. Explain why quantize(Decimal("0.05")) alone does not guarantee rounding to a five-cent multiple.

Show hint

The quantizer supplies an exponent rather than a general increment.

Show worked solution

Decimal("0.05") has exponent -2, so quantize selects two decimal places. It does not force the result to be divisible by 0.05; an explicit increment-rounding calculation is required for that policy.

Check your solution

  • The exponent selected is -2
  • A multiple of 0.05 is not guaranteed

13. Round the synthetic amount 1.22 to the nearest 0.05 using half-up rounding of increment units.

Show hint

Divide by 0.05, round to an integer, then multiply by 0.05.

Show worked solution

1.22 / 0.05 is 24.4. Half-up integral rounding gives 24, and multiplying by 0.05 yields 1.20. Validate this policy and its units separately for the intended application. Check the exact value and the stated rounding policy.

Check your solution

  • The rounded increment count is 24
  • The resulting amount is 1.20

14. Two items each have value 0.005. Round each half up to cents and then add them.

Show hint

Apply the cent quantization to each item before summing.

Show worked solution

Each item rounds from 0.005 to 0.01 using ROUND_HALF_UP. Adding the two rounded results gives 0.02. This is a line-by-line policy and may differ from rounding the total once. Check the exact value and the stated rounding policy.

Check your solution

  • Each rounded item is 0.01
  • The line-rounded total is 0.02

15. Two items each have value 0.005. Sum them first and then round half up to cents.

Show hint

Add the exact decimal inputs before quantizing the total.

Show worked solution

The decimal sum is 0.010. Quantizing the sum to Decimal("0.01") with ROUND_HALF_UP gives 0.01. This differs from the result when each item is rounded separately first. Check the exact value and the stated rounding policy.

Check your solution

  • The unrounded sum is 0.010
  • The rounded total is 0.01

16. In a local context with precision 3, calculate Decimal("1") / Decimal("8") and state what precision means.

Show hint

Precision counts significant digits for arithmetic.

Show worked solution

The exact quotient is 0.125, which fits three significant digits, so the result is 0.125. Context precision refers to significant digits rather than simply specifying three digits after every decimal point.

Check your solution

  • The result is 0.125
  • The precision is three significant digits

17. Describe how to handle Decimal("invalid") under the usual context without treating it as zero.

Show hint

Malformed decimal text can raise InvalidOperation.

Show worked solution

Construction raises InvalidOperation for this malformed text under the usual context. Catch or report that input error according to the application contract; do not silently substitute zero and continue a calculation.

Check your solution

  • The error is InvalidOperation
  • The invalid input is not silently replaced with zero

18. Check whether Decimal("3.20") and Decimal("Infinity") are finite before accepting them as amounts.

Show hint

Use is_finite on each decimal value.

Show worked solution

Decimal("3.20").is_finite() is True, while Decimal("Infinity").is_finite() is False. A finite-only amount contract accepts the first on this check and rejects the second before further domain validation. Check the exact value and the stated rounding policy.

Check your solution

  • 3.20 is finite
  • Infinity is not finite

19. Explain why Decimal("0.1") can differ from Decimal(0.1) despite their similar source spelling.

Show hint

The latter constructor receives a binary float approximation.

Show worked solution

The string constructor gives the exact decimal value one tenth. Decimal(0.1) receives and exactly converts the already approximated binary float, so the resulting decimal is not numerically identical to Decimal("0.1").

Check your solution

  • The string input is exact one tenth
  • The float conversion preserves its approximation

20. Quantize Decimal("0") to cents with ROUND_HALF_UP and state the displayed result. Explain the result and the stated rounding rule.

Show hint

Use Decimal("0.01") as the target exponent.

Show worked solution

The result is Decimal("0.00"), displayed as 0.00. Its numerical value is still zero, but quantize sets the exponent to -2 to match the requested cent scale. Check the exact value and the stated rounding policy.

Check your solution

  • The displayed result is 0.00
  • The resulting exponent is -2

Key takeaways

  • Decimal text preserves decimal intent at construction.
  • Rounding point and mode are domain decisions.
  • A rounding rule needs an explicit target exponent, mode, and calculation stage.
  • Constructing Decimal from a float preserves the float approximation.
  • quantize matches an exponent; a five-cent increment requires an explicit policy.

Official references