gpt4 book ai didi

c# - 如何舍入十进制值列表?

转载 作者:行者123 更新时间:2023-12-02 05:36:12 27 4
gpt4 key购买 nike

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

谢谢,文卡特斯

最佳答案

基本上,

The sum of rounded figures is not necessarily equal the rounded sum of the same figures.

你只需要在最后一轮。

这将为您提供预期的输出:

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

我得到以下输出:

output

关于c# - 如何舍入十进制值列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11644381/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com