I have a list of double values, I want to Round a variable's value to only that list of numbers
Example:
The list contents are: {12,15,23,94,35,48}
The Variable's value is 17, So it will be rounded to 15
If The variable's value is less than the least number, it will be rounded to it, if it's value is larger than the largest number, it will be rounded to it.
The list contents is always changing according to an external factor, So I cannot hardocde the values I Want to round up or down to.
How can do it in C# ?
In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).
The round( ) function in the C programming language provides the integer value that is nearest to the float, the double or long double type argument passed to it. If the decimal number is between “1 and. 5′′, it gives an integer number less than the argument.
Round() Method | Set – 2. In C#, Math. Round() is a Math class method which is used to round a value to the nearest integer or to the particular number of fractional digits.
Here's a method using LINQ:
var list = new[] { 12, 15, 23, 94, 35, 48 };
var input = 17;
var diffList = from number in list
select new {
number,
difference = Math.Abs(number - input)
};
var result = (from diffItem in diffList
orderby diffItem.difference
select diffItem).First().number;
EDIT: Renamed some of the variables so the code is less confusing...
EDIT:
The list
variable is an implicitly declare array of int
. The first LINQ statement diffList
defines an anonymous type that has your original number from the list (number
) as well as the difference between it and your current value (input
).
The second LINQ statement result
orders that anonymous type collection by the difference, which is your "rounding" requirement. It takes the first item in that list as it will have the smallest difference, and then selects only the original .number
from the anonymous type.
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