Last active
May 26, 2022 15:17
-
-
Save glaidler/c40de34c9f216cdbe95b20e55b087f24 to your computer and use it in GitHub Desktop.
decimal-split
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
public class Program | |
{ | |
// from https://stackoverflow.com/questions/67067274/how-to-divide-a-decimal-number-into-rounded-parts-that-add-up-to-the-original-nu | |
public static IEnumerable<decimal> RoundedDivide(decimal amount, int count) | |
{ | |
int totalCents = (int)Math.Floor(100 * amount); | |
// work out the true division, integer portion and error values | |
float div = totalCents / (float)count; | |
int portion = (int)Math.Floor(div); | |
float stepError = div - portion; | |
float error = 0; | |
for (int i = 0; i < count; i++) | |
{ | |
int value = portion; | |
// add in the step error and see if we need to add 1 to the output | |
error += stepError; | |
if (error > 0.5) | |
{ | |
value++; | |
error -= 1; | |
} | |
// convert back to dollars and cents for outputput | |
yield return value / 100M; | |
} | |
} | |
public static void Main() | |
{ | |
var spread = RoundedDivide(7.29m, 365); | |
var index = 1; | |
foreach(var i in spread){ | |
Console.WriteLine($"{index}: {i}"); | |
index++; | |
} | |
Console.WriteLine($"Total: {spread.ToList().Sum()}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment