Evenly divide a dollar amount (decimal) by an inte

2019-03-09 08:42发布

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?

8条回答
看我几分像从前
2楼-- · 2019-03-09 09:14

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
查看更多
We Are One
3楼-- · 2019-03-09 09:16

Take a look at this question: What is the best data type to use for money in c#?

Wait a second! You want to make sure that not a single cent gets lost, right?

查看更多
登录 后发表回答