您能否解释一下如何将我的十进制列表格式化为两位小数&总数应该是100.00?
static void Main(string[] args)
{
string decimalFormat = "0.00";
decimal[] individuals = { 10, 10, 10 };
decimal total = 30;
List<decimal> percents = new List<decimal>();
foreach (decimal t in individuals)
{
decimal percent = (t * 100) / total;
percents.Add(percent);
}
List<decimal> roundToTwoDecimalPercent = new List<decimal>();
foreach (decimal portfolio in percents)
{
roundToTwoDecimalPercent.Add(Math.Round(portfolio, 2));
}
decimal percentTotal = decimal.Zero;
foreach (decimal final in roundToTwoDecimalPercent)
{
percentTotal += final;
}
Console.WriteLine(percentTotal.ToString(decimalFormat)); // 99.99 but the EXPECTED OUTPUT IS 100.00
Console.ReadLine();
}
谢谢, S.Venkatesh
答案 0 :(得分:5)
基本上,
四舍五入的总和不一定等于相同数字的四舍五入。
你最后只需要进行一次。
这将为您提供预期的输出:
static void Main(string[] args)
{
string decimalFormat = "0.00";
decimal[] individuals = { 10, 10, 10 };
decimal total = 30;
List<decimal> percents = new List<decimal>();
foreach (decimal t in individuals)
{
decimal percent = (t * 100) / total;
percents.Add(percent);
}
decimal percentTotal = decimal.Zero;
foreach (decimal percent in percents)
{
percentTotal += percent;
}
Console.WriteLine(string.Format("{0:N2}", percentTotal));
Console.ReadLine();
}
OR:如果你是像我一样的LINQ粉丝,这会给你相同的结果:
static void Main(string[] args)
{
decimal[] individuals = { 10, 10, 10 };
decimal total = individuals.Sum();
decimal[] percentages = individuals.Select(i => i * 100 / total).ToArray();
decimal percentageTotal = percentages.Sum();
Console.WriteLine(string.Format("{0:N2}", percentageTotal));
Console.ReadLine();
}
其他示例:使用以下测试应用:
static void Main(string[] args)
{
decimal[] individuals = { 10, 10, 10 };
Console.WriteLine("Unrounded figures");
var percentages = individuals.Select(i => i * 100 / individuals.Sum()).ToList();
percentages.ForEach(p => Console.WriteLine(p.ToString()));
decimal percentageTotal = percentages.Sum();
Console.WriteLine("Their unrounded sum = {0}", percentageTotal);
Console.WriteLine("Their rounded sum = {0:N2}", percentageTotal);
Console.WriteLine();
Console.WriteLine("Rounded figures");
var roundedPercentages = individuals.Select(i => Math.Round(i * 100 / individuals.Sum(), 2)).ToList();
roundedPercentages.ForEach(p => Console.WriteLine(p.ToString()));
decimal roundedPercentageTotal = roundedPercentages.Sum();
Console.WriteLine("Their unrounded sum = {0}", roundedPercentageTotal);
Console.WriteLine("Their rounded sum = {0:N2}", roundedPercentageTotal);
Console.ReadLine();
}
我得到以下输出: