2

你能解释一下如何将我的小数列表格式化为两位小数并且总数应该是 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

4

1 回答 1

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();
}

或者:如果你像我一样是一个 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();
}

我得到以下输出:

输出

于 2012-07-25T07:20:31.070 回答