I’m trying to do some number formatting and I’m looking for an elegant way to format numbers in a list. As an example here is my list:
List<double> list =
new List<double>(new double[] {34.8, 35.0, 35.7, 35.9, 38.0});
If I print these using list.ForEach(x => Console.WriteLine(x.ToString("#"))) I get:
35
35
36
36
38
Which isn’t exactly correct. I want to display the minimum number of significant figures to ensure that each result is unique (Assuming no duplicates). So for the above, the formatting string would be “#.#” so that I get one decimal.
If these are the numbers: {35, 37, 40, 41, 42} I don’t want to use “#.#” I want to use “#” because I don’t want to waste space by printing out the “.0” when it doesn’t really matter.
I’m only strictly worried about the number digits to the left of the decimal.
This is my hacked together code, but I’m hoping there is a more elegant way to do this. I’m basically trying to optimize this:
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 += "#";
}
}
1 Answer