Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evenly divide a dollar amount (decimal) by an integer

I need to write an accounting routine for a program I am building that will give me an even division of a decimal by an integer. So that for example:

$143.13 / 5 =

28.62
28.62
28.63
28.63
28.63

I have seen the article here: Evenly divide in c#, but it seems like it only works for integer divisions. Any idea of an elegant solution to this problem?

like image 352
Amberite Avatar asked Jan 11 '10 01:01

Amberite


People also ask

How do you evenly divide money?

50/50. This one is as simple as it sounds. Everything is split right down the middle, or equally between the number of roommates. In an ideal world, the people who opt for this method earn generally equal salaries and use an equal amount of the home's resources, i.e. groceries, utilities and living space.


1 Answers

Calculate the amounts one at a time, and subtract each amount from the total to make sure that you always have the correct total left:

decimal total = 143.13m;
int divider = 5;
while (divider > 0) {
  decimal amount = Math.Round(total / divider, 2);
  Console.WriteLine(amount);
  total -= amount;
  divider--;
}

result:

28,63
28,62
28,63
28,62
28,63
like image 59
Guffa Avatar answered Sep 29 '22 20:09

Guffa