Make Category Percentages Represent Total Spending
Open:
client/src/lib/categoryTotals.js
client/src/components/CategoryBreakdown.jsx
The starter category breakdown compares each category with the largest category. That means the largest category is always 100%.
That percentage is relative, but it does not answer a useful financial question. We want it to mean:
What share of all expense spending belongs to this category?
Start by totaling only expenses by category:
const totals = {};
transactions.forEach((transaction) => {
if (transaction.type !== "expense") return;
totals[transaction.category] =
(totals[transaction.category] || 0) + transaction.amount;
});
Then calculate the total expense across all categories:
const totalExpense = Object.values(totals).reduce(
(sum, amount) => sum + amount,
0
);
For each category, calculate its share of that total:
const total = totals[category.name] || 0;
return {
...category,
total,
pct: totalExpense > 0 ? total / totalExpense : 0,
};
The totalExpense > 0 check prevents division by zero when there are no expenses.
The component already converts pct into a bar width:
style={{
width: `${category.pct * 100}%`,
background: category.color,
height: "100%",
}}
With the seeded data:
Housing $1,150.00
Food $84.50
Utilities $62.00
Transport $46.00
Entertainment $24.00
The total is $1,366.50, so Housing represents approximately:
1150 / 1366.50 ≈ 0.842
That becomes a bar of about 84%.
This calculation is more meaningful because its denominator stays tied to total spending, not whichever category happens to be largest.
Test it
Open the Ledger and inspect spending by category. Housing should be about 84%, not 100%.
Add an expense in another category. Both that category’s amount and its share should change.
Checkpoint
The category percentage now has a clear financial meaning: each bar represents that category’s share of total expenses.