如何使我的 writeline 输出显示最接近小数点后两位的数值?

How do I make my writeline output display the numeric value to the nearest 2 decimal?

我只是需要为我的任务完成这个程序,我已经完成了我想要它执行的任务,但我终究无法弄清楚如何让我的输出显示数字值第二位小数。 (例如:35.50)

我的程序旨在取值的平均值,并以小数形式给出平均值。它确实这样做了,但是十进制字符串比 2 个小数位长。我希望得到一些关于如何清理它的建议,请给出所有答案并附上解释。太感谢了! (我使用的程序是visual studios 2017,我在C#的控制台应用程序中创建这段代码)

static void Main(string[] args)
    {

        decimal counter = 1;
        decimal sum = 0;
        decimal totalLoops = 3;


        while (counter <= totalLoops)
        {
            Console.WriteLine("Please enter test score here:");
            string scoreInput = Console.ReadLine();
            decimal score;
            decimal.TryParse(scoreInput, out score);
            sum += score;
            counter++;

        }

        Console.WriteLine("Your average is {0}", decimal.Round(sum, 2) / decimal.Round(totalLoops, 2));
        Console.ReadKey();

    }

}

您可以使用Math.Round

Console.WriteLine("Your average is {0}", Math.Round(decimal.Round(sum, 2) / decimal.Round(totalLoops, 2), 2, MidpointRounding.AwayFromZero));

{0:N2} 根据您的区域设置获得 2 位小数。 (标准方式)

{0:0.00} 总是得到 2 位小数,例如:2.00 将显示 2.00。

{0:0.##} 显示 2 位小数(如果它们不为零),例如:2.00 将显示 2.

请阅读这些以供参考:

您想强制字符串显示小数。

此外,您可能只想对平均值的结果进行四舍五入。

Console.WriteLine("Your average is {0:N2}", sum/totalLoops);