How to sort list of doubles by the fractional part of the double.
E.g: For input <1.2, 2.3, 1.12, 5.1>
, after sorting, the output
should be <5.1, 1.12, 1.2, 2.3>
<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .
%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.
You can achieve this through OrderBy()
and Math.Truncate()
method as like the following. Where x-Math.Truncate(x)
gives you the number after the decimal point and OrderBy
will arrange them in the ascending order. Have a look at this example and try yourself with the following snippet
List<double> input = new List<double>(){1.2, 2.3, 1.12, 5.1};
input = input.OrderBy(x=>x-Math.Truncate(x)).ToList();
Console.WriteLine(String.Join("\n",input));
Or you can try this as well .OrderBy(x=>x-(int)x)
instead for OrderBy(x=>x-Math.Truncate(x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With