Thanks you for reaching out!
I have a list of doubles:
List<double> list = new List<double>()
{
2.7, -3.5, 0.6, 34.83, 7.458, 0, 9.20, -20.40, 12.2
};
How can I retrieve the number that contains the most digits after the comma? (in this case 7.458)
What I tried so far was to declare a DecimalSeparator
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";
and to try and Split (using LINQ) every number from the list
list.Split(nfi);
but I can't do that because it's a list of doubles, should I convert the list to a list of strings and then go from there? Or is it another method that I don't know about...
Thanks in advance for the response! Have a great day! :D
(Sorry if the question is too basic... I'm new to C# :c )
CodePudding user response:
Here is a more simple, basic approach:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<double> list = new List<double>()
{
2.7, -3.5, 0.6, 34.83, 7.458, 0, 9.20, -20.40, 12.2
};
int digits = 0;
double nr = Double.NaN;
for(int i = 0; i < list.Count; i)
{
if((list[i] % 1) == 0) continue; // If the number does not have digits: 5.0, 3.0, 7, etc.
// https://stackoverflow.com/questions/2751593/how-to-determine-if-a-decimal-double-is-an-integer
string nrstring = list[i].ToString();
string aftercomma = nrstring.Split('.')[1];
if(aftercomma.Length > digits)
{
digits = aftercomma.Length;
nr = list[i];
}
}
Console.WriteLine(nr);
}
}
This is the fiddle.
CodePudding user response:
Here's a possible solution:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<double> list = new List<double>()
{
2.7, -3.5, 0.6, 34.83, 7.458, 0, 9.20, -20.40, 12.2, 0.000000002
};
var max = list
.Select(n => ((decimal)n).ToString().Split('.').ElementAtOrDefault(1))
.Where(n => n != null)
.Select(n => new { Number = n, Length = n.Length })
.OrderByDescending(n => n.Length)
.First();
Console.WriteLine(max); // { Number = 000000002, Length = 9 }
}
}
I doubt that you'll need to worry about the ToString conversion and back too much - this should only become relevant at huge list sizes. If that's your concern then you could try to work with the binary representation of the number directly instead. Note that this might reduce the 'straight-forwardness' of the solution and impact maintainability in the long run if not documented properly.
Edit 1: Edited code to reflect comment and support leading zeros. Note: decimal casting necessary to prevent scientific notation up to a number of decimal places.
