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
难道我要显示小数点列表[百分之每33.33即作为小数点后两位,那么它不会等于100% – user1531248 2012-07-25 07:27:16
显然不是。当您计算总和时,使用** unrounded **数字 - 然后当您将结果舍入时,它将被正确计算。经验法则是,在计算时不要使用四舍五入的数字。当你**向用户呈现**时,只有圆形数字。 – tobias86 2012-07-25 07:32:21
@ user1531248:查看我更新的答案。我发布了一个例子,展示了当您处理圆形和未被遮挡的数字时的不同之处。 – tobias86 2012-07-25 07:39:19