Code

Exact Money

Floats are stored in binary, and most decimal fractions can't be represented exactly:

print(0.1 + 0.2)   # 0.30000000000000004

Fine for physics, terrible for a guild ledger. Use decimal.Decimal:

from decimal import Decimal, ROUND_HALF_UP

total = Decimal("0.10") + Decimal("0.20")
print(total)                    # 0.30

price = Decimal("2.675")
cents = Decimal("0.01")
price.quantize(cents, rounding=ROUND_HALF_UP)   # Decimal('2.68')

Rules of thumb:

  • Build Decimals from strings (Decimal("0.1")), never from floats, Decimal(0.1) faithfully copies the float's tiny error.
  • quantize(Decimal("0.01")) rounds to cents. The default rounding is "banker's rounding" (half to even), so say ROUND_HALF_UP if you want school-style rounding.
  • Decimals mix with ints (Decimal("2.5") * 3) but not floats.

For exact ratios, use fractions.Fraction: Fraction(2, 8) is automatically reduced to Fraction(1, 4), and Fraction(1, 3) * 3 == 1.

Assignment

  1. cart_total(prices): prices is a list of strings like "4.10". Return their sum as a Decimal.
  2. with_tax(amount, rate): amount is a Decimal, rate is a percent string like "7.5". Return amount plus tax, rounded to cents with ROUND_HALF_UP.
  3. mix_ratio(a, b): a potion uses a parts moonwater and b parts oil. Return the moonwater share of the whole as a Fraction.