
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 sayROUND_HALF_UPif 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
cart_total(prices):pricesis a list of strings like"4.10". Return their sum as aDecimal.with_tax(amount, rate):amountis aDecimal,rateis a percent string like"7.5". Returnamountplus tax, rounded to cents withROUND_HALF_UP.mix_ratio(a, b): a potion usesaparts moonwater andbparts oil. Return the moonwater share of the whole as aFraction.
cart_total(prices):pricesis a list of strings like"4.10". Return their sum as aDecimal.with_tax(amount, rate):amountis aDecimal,rateis a percent string like"7.5". Returnamountplus tax, rounded to cents withROUND_HALF_UP.mix_ratio(a, b): a potion usesaparts moonwater andbparts oil. Return the moonwater share of the whole as aFraction.
main.py Python sleeping
Press Run to try your code, then Check to test it.