5
\$\begingroup\$

This relates to Round to specified int but I'm separating these methods out since they're technically different.

Is there a method that already performs a custom floor and ceiling to a specified integer?

// If the interval is 5, 9 --> 5.
public static int FloorTo(this int value, int interval)
{
    var remainder = value % interval;
    return remainder > 0 ? value - remainder : value; 
}

// If the interval is 5, 6 --> 10.
public static int CeilingTo(this int value, int interval)
{ 
    var remainder = value % interval;
    return remainder > 0 ? value + (interval - remainder) : value;
}
\$\endgroup\$
5
\$\begingroup\$
  1. Your methods take int parameters but it seems like you only have really thought about positive numbers. This yields some inconsistencies. For example:

    • (-28).FloorTo(6) == -28
    • (-28).FloorTo(-6) == -28
    • (28).FloorTo(-6) == 24

    For CeilingTo the results are:

    • (-28).CeilingTo(6) == -28
    • (-28).CeilingTo(-6) == -28
    • (28).CeilingTo(-6) == 18

    If you don't want to think about or deal with negative numbers you should either change the signature to accept only uint parameters (which would require the caller to think about what to do in case he's got an int) or you check and throw an ArgumentOutOfRange exception

  2. Just considering positive numbers FloorTo could be changed to

    public static int FloorTo(this int value, int interval)
    {
       var remainder = value % interval;
       return value - remainder;
    }
    

    Less logic to read and verify in your head.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.