What is the best way to solve this problem in code?
The problem is that I have an amount of $ 2 (known as a bank) that I need to allocate to 3 people. Each person receives a certain amount, which comes from both pots, and the rates should be approximately the same. I continue to encounter rounding issues when my allocation is either too complicated or too small.
Here is an example:
Pot No. 1 987 654.32
Pot No. 2 123 456.78
Person No. 1 receives the appropriation amount: 345,678.89
Person No. 2 receives the appropriation amount: 460 599.73
Person No. 3 receives the appropriation amount: 304,832.48
My logic is as follows (code is in C #):
foreach (Person person in People) { decimal percentage = person.AllocationAmount / totalOfAllPots; decimal personAmountRunningTotal = person.AllocationAmount; foreach (Pot pot in pots) { decimal potAllocationAmount = Math.Round(percentage * pot.Amount, 2); personAmountRunningTotal -= potAllocationAmount; PersonPotAssignment ppa = new PersonPotAssignment(); ppa.Amount = potAllocationAmount; person.PendingPotAssignments.Add(ppa); } foreach (PersonPotAssignment ppa in person.PendingPotAssignments) { if (personAmountRunningTotal > 0)
The results I get are as follows:
Pot No. 1, Person No. 1 = 307,270.13
Pot No. 1, Person No. 2 = 409,421.99
Pot No. 1, Person No. 3 = 270 962.21
Pot No. 1 Total = 987 654.33 (1 penny)
Pot No. 2, Man No. 1 = 38,408.76
Pot No. 2, Person No. 2 = 51,177.74
Pot No. 2, Person No. 3 = 33,870.27
Pot No. 2 Total = 123,456.77 (1 kopeck)
The results of the sweat should correspond to the initial totals.
I think I can miss something, or there may be an extra step that I need to take. I think I'm on the right track.
Any help would be greatly appreciated.