Floor and Ceiling to specified int

Posted on

Problem

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;
}

Solution

  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.

Leave a Reply

Your email address will not be published. Required fields are marked *