Search code examples
c#.netroundingdiscrete-mathematicsdiscretization

Round to the nearest number in an interval centered around 100


I want to round a number (up or down) in an inputted interval centered around 100 (not exactly on the multiples of the internal length). Here are some examples:

Ex 1: Length=3, Center=100, Input=99.76, Round Down=True => The discrete interval is [..., 97, 100, 103,...] and the Output=97.

Ex 2: Length=4, Center=100, Input=95.5, Round Down=False => The discrete interval is [..., 96, 100, 104,...] and the Output=96

Ex 3: Length=6, Center=100, Input=101.1, Round Down=False => The discrete interval is [..., 94, 100, 106,...] and the Output=106

I have an idea of generating the interval and then rolling though using a loop and finding the first value.

How would I do this in C#?

What I've tried:

Result = Length* (int) Math.Ceiling(Input / Length)

The issue is that this looks at the multiples of the length, but it doesn't center it at 100.

I think I need something like this, but it needs to handle all cases of numbers:

Result = Center + Length* (int) Math.Ceiling(Math.Abs(Center -Input) / Length)

That seems to work for numbers greater than Center, but fails in other cases.


EDIT: I think this works in all cases:

Result = Center + Length* (int) Math.Ceiling((Input - Center) / Length)

Solution

  • I'd do something like this:

    int Round(int length, int center, decimal input, bool roundDown)
    {
        return length * (int)(roundDown ? Math.Floor((input - (decimal)center) / length) 
                                      : Math.Ceiling((input - (decimal)center) / length))
              + center;
    }