Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/libs/IOUUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,18 @@ function calculateAmount(numberOfSplits: number, total: number, currency: string
* Calculate a split amount in backend cents from a percentage of the original amount.
* - Clamps percentage to [0, 100]
* - Preserves decimal precision in percentage (supports 0.1 precision)
* - Uses absolute value of the total amount (cents)
* - Preserves the sign of the original amount (negative amounts stay negative)
*/
function calculateSplitAmountFromPercentage(totalInCents: number, percentage: number): number {
const totalAbs = Math.abs(totalInCents);
// Clamp percentage to [0, 100] without rounding to preserve decimal precision
const clamped = Math.min(100, Math.max(0, percentage));
return Math.round((totalAbs * clamped) / 100);
const amount = Math.round((totalAbs * clamped) / 100);
// Return 0 for zero amounts to avoid -0
if (amount === 0) {
return 0;
}
return totalInCents < 0 ? -amount : amount;
}

/**
Expand Down
14 changes: 12 additions & 2 deletions tests/unit/IOUUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,10 +185,20 @@ describe('IOUUtils', () => {
expect(IOUUtils.calculateSplitAmountFromPercentage(8900, 7.7)).toBe(685);
});

test('Clamps percentage between 0 and 100 and uses absolute total', () => {
test('Clamps percentage between 0 and 100', () => {
expect(IOUUtils.calculateSplitAmountFromPercentage(20000, -10)).toBe(0);
expect(IOUUtils.calculateSplitAmountFromPercentage(20000, 150)).toBe(20000);
expect(IOUUtils.calculateSplitAmountFromPercentage(-20000, 25)).toBe(5000);
});

test('Preserves negative sign for negative amounts (negative expense splits)', () => {
// When the original transaction is negative, split amounts should also be negative
expect(IOUUtils.calculateSplitAmountFromPercentage(-20000, 25)).toBe(-5000);
expect(IOUUtils.calculateSplitAmountFromPercentage(-20000, 50)).toBe(-10000);
expect(IOUUtils.calculateSplitAmountFromPercentage(-10000, 33.3)).toBe(-3330);
// Edge case: 0% results in 0 amount (not -0)
expect(IOUUtils.calculateSplitAmountFromPercentage(-20000, 0)).toBe(0);
// Full amount should also be negative
expect(IOUUtils.calculateSplitAmountFromPercentage(-20000, 100)).toBe(-20000);
});
});

Expand Down
Loading