【问题标题】:How do I make my writeline output display the numeric value to the nearest 2 decimal?如何让我的 writeline 输出显示数值到最接近的 2 位小数?
【发布时间】:2020-01-19 22:46:36
【问题描述】:

我只需要为我的作业完成这个程序,并且我已经完成了我希望它执行的任务,但我一生无法弄清楚如何让我的输出显示数字值到秒十进制。 (例如: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();

    }

}

【问题讨论】:

  • "Your average is {0:N2}"
  • 访问stackoverflow.com/questions/15288134/… *value.ToString("0.00");
  • 我还强烈建议不要在进行数学计算时进行舍入直到最后一次可能的计算。换句话说,不要将两个数字四舍五入然后除以它们。相反,在最后进行除法和舍入 一次 以获得输出(或使用我建议的技术来避免显式舍入的需要)。

标签: c# decimal console-application rounding


【解决方案1】:

您可以使用Math.Round

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

【讨论】:

  • 这非常有效。您能否解释一下为什么 math.round 会去哪里以及 MidpointRounding.AwayFromZero 会做什么?我想了解。 :) 谢谢。
  • 你可以用谷歌搜索 MidpointRounding.AwayFromZero 对 @brainpain 做了什么。基本上它从 0.5 向上舍入,而不是做银行家舍入。
  • 如果四舍五入的数字要用于进一步的计算,您应该只进行四舍五入,尤其是因为日志记录代码变得不那么惯用和可读性。此外,如果 sum 仅定义为小数点后一位(例如,35.5),那么这将打印 35.5,而不是原始问题中所需的 35.50
【解决方案2】:

{0:N2} 根据您的语言环境获得 2 位小数。 (标准方式)

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

{0:0.##} 显示 2 个非零小数,例如:2.00 将显示 2。

请阅读以下内容以供参考:

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-05-24
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2014-11-26
      • 2015-12-10
      相关资源
      最近更新 更多