Skip to main content
 首页 » 编程设计

C# 最小有效数字数

2024年02月23日17lexus

我正在尝试进行一些数字格式化,并且正在寻找一种优雅的方式来格式化列表中的数字。作为示例,这是我的列表:

List<double> list = 
   new List<double>(new double[] {34.8, 35.0, 35.7, 35.9, 38.0}); 

如果我使用 list.ForEach(x => Console.WriteLine(x.ToString("#"))) 打印这些,我得到:

35 
35 
36 
36 
38 

这不完全正确。我想显示最少数量的有效数字以确保每个结果都是唯一的(假设没有重复)。因此,对于上面的内容,格式字符串将是“#.#”,以便我得到一位小数。

如果这些是数字:{35, 37, 40, 41, 42} 我不想使用“#.#”我想使用“#”因为我不想不想在无关紧要的情况下打印出“.0”来浪费空间。

我只非常担心小数点左边的数字。

这是我编写的代码,但我希望有更优雅的方法来执行此操作。我基本上是在尝试优化它:

bool unique = false; 
string format = "#." 
List<string> strings = new List<string>(); 
 
while (!unique) 
{ 
   strings = List.Select(x => x.ToString(format)).Distinct().ToList(); 
 
   if (strings.Count() == list.County()) 
   { 
     unique = true; 
   } 
   else 
   { 
     format += "#"; 
   } 
} 

请您参考如下方法:

string format = "#."; 
while (list.GroupBy(x => x.ToString(format)) 
           .Any(g => g.Count() > 1) 
      ) { 
    format += "#"; 
}