Divide decimal currency evenly
Division where reminder is redistributed among results so that average delta is minimal.
Source
public static IEnumerable<decimal> DivideEvenly(this decimal total, int count, int round = 2)
{
while (count > 0)
{
decimal value = Math.Round(total / count, round);
total -= value;
count--;
yield return value;
}
}
Example
var value = 26M;
var count = 6;
var round = 2;
var expected = new decimal[] { 4.33M, 4.33M, 4.34M, 4.33M, 4.34M, 4.33M };
var actual = value.DivideEvenly(count, round).ToArray();
Assert.Equal(expected, actual);
Author: LittleNetworkHack
Submitted on: 7 dec. 2021
Language: csharp
Type: System.Decimal
Views: 13740