Alex Rivera | Logout

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

Asked 2011-10-23T11:26:57.493
10

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

Edit
Report

1 Answer

1

Do something like this:

double distance = double.PositiveInfinity;
float roundedValue = float.NaN;
foreach (float f in list)
{
    double d = Math.Abs(d - f);
    if (d < distance)
    {
        distance = d;
        roundedValue = f;
    }
}
answered 2011-10-23T11:38:44.117

Your Answer