【问题标题】:Format four decimal places in C#在 C# 中格式化四位小数
【发布时间】:2021-06-10 21:18:03
【问题描述】:

我有这个算法,我需要将其格式化为小数点后 4 个小数位,我该如何做这个算法?

假设输入是:2.00,那么我的输出一定是 12.5664

static void Main(string[] args)
        {
            double n = 3.14159;
            double raio = double.Parse(Console.ReadLine());

            double area = n * Math.Pow(Convert.ToDouble(raio), 2);

            Console.WriteLine($"A={area}");
        }

【问题讨论】:

  • .ToString("N4")
  • 你需要说什么没用。
  • 此方案有效,只需添加double raio = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);

标签: c# .net algorithm data-structures logic


【解决方案1】:

双面积=123.4567;

// 最大值两位小数

String.Format("{0:0.####}", area); // "123.4567"

String.Format("{0:0.##}", area); // "123.46"

String.Format("{0:0}", area); // "123"

【讨论】:

  • 考虑最后一个应该是 String.Format("{0:0}", area); // "123"

【解决方案2】:

您可以将其作为格式字符串传递给您想要的小数位数:

        double n = 3.14159;
        double raio = double.Parse(Console.ReadLine());
        
        //fixed converting a double from a variable that was already a double
        double area = n * Math.Pow(raio, 2);

        Console.WriteLine($"A={area.ToString("#.####")}");

        //if you need to get the rounded number to do another calculation with
        double roundedArea = Double.Parse(area.ToString("#.####"));

【讨论】:

  • 我用这种方法进行了测试,但这是一种代码味道,我用 ToString ("F4") 尝试过,答案被更好地接受了
  • @Dolla 没有异味,这是一种标准的格式化功能。被什么“更好地接受”?
  • 我在一个在线代码站点上,当发送代码时,答案是“错误答案”,由于某种原因 ToString("F4") 答案是“接受”
  • Convert.ToDouble(something-that-is-already-a-double) 是一种实际代码味道,而且在 imo 上更糟
猜你喜欢
  • 2015-01-04
  • 2011-03-27
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
相关资源
最近更新 更多