void Main() { var shares = GetNicePercentagesForShares(0.01, 2, 3, 4); var total = shares.Sum(); foreach(var share in shares) Console.WriteLine($"{share}%"); Console.WriteLine($"total: {total}%"); } // 1% // 22% // 33% // 44% // total: 100% public static List<double> GetNicePercentagesForShares(params double[] shares) { var total = shares.Sum(); if (total <= 0) return shares.Select(i => 0.0).ToList(); var onePercent = 100.0 / total; var smallEnough = 0.0000001; var percentages = shares.Select(s => { var percentage = Math.Round(s * onePercent); if (s > smallEnough && percentage < 1) percentage = 1; // If there is a share display at least 1 percent return percentage; }).ToList(); var percentTotal = percentages.Sum(); // correct the largest percentage if (Math.Abs(percentTotal - 100.0) > double.Epsilon) { int largestPercentageIndex = percentages.IndexOf(percentages.Max()); percentages[largestPercentageIndex] = (100.0 - percentTotal); } return percentages; }
11900cookie-checkC# Nice percentages