Python Project: A Budget Tracker
A budget tracker is a program that adds up money spent. It uses Decimal amounts, so the totals come out exact.
Floats round money badly
Plain floats cannot hold 0.1 exactly. The sum shows the leftover error.
print(0.1 + 0.2)Decimal keeps it exact
Decimal("0.1") and Decimal("0.2") add to exactly 0.3. The error is gone.
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))Add a list of amounts
The loop adds each Decimal to the running total. The printout is the exact sum.
from decimal import Decimal
spending = [Decimal("12.50"), Decimal("3.25"), Decimal("8.00")]
total = Decimal("0")
for amount in spending:
total = total + amount
print("Total:", total)Example
from decimal import Decimal
expenses = [
{"category": "Food", "amount": Decimal("12.50")},
{"category": "Bus", "amount": Decimal("3.25")},
{"category": "Food", "amount": Decimal("8.00")},
{"category": "Books", "amount": Decimal("15.99")},
]
totals = {}
grand = Decimal("0")
for expense in expenses:
name = expense["category"]
if name not in totals:
totals[name] = Decimal("0")
totals[name] = totals[name] + expense["amount"]
grand = grand + expense["amount"]
for name in sorted(totals):
print(name, totals[name])
print("Grand total:", grand)Key points
- Decimal: a number type for exact money maths, from the decimal module
- Use Decimal("12.50") to make an exact amount from text
- Use a list of dicts to hold the spending, with a category and an amount in each dict
- Add Decimals with +, just like plain numbers
- Use a dict to hold one total per category
- Sort the category names before printing, so the order stays the same
In this example, the expenses list holds four dicts, each with a category and a Decimal amount. The loop adds each amount to its category total and to the grand total. The totals dict starts a category at zero the first time it meets one. The sorted printout lists each category total in name order. The grand total of 39.74 is the exact sum of all four amounts.
Note
Plain floats round money badly. 0.1 + 0.2 gives 0.30000000000000004, not 0.3.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Why does the tracker use Decimal for money?