Skip to content

Instantly share code, notes, and snippets.

@glaidler
Last active May 26, 2022 15:17
Show Gist options
  • Save glaidler/c40de34c9f216cdbe95b20e55b087f24 to your computer and use it in GitHub Desktop.
Save glaidler/c40de34c9f216cdbe95b20e55b087f24 to your computer and use it in GitHub Desktop.
decimal-split
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