Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding a value to only a list of certain values in C#

Tags:

c#

.net

math

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# ?

like image 394
smohamed Avatar asked Oct 23 '11 11:10

smohamed


People also ask

How do you get the C to round up?

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).

What does round function do in C?

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.

How do you round to next whole number in C#?

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.


1 Answers

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.

like image 91
Yuck Avatar answered Oct 11 '22 17:10

Yuck