HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Floor and Ceiling to specified int

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andintceilingspecifiedfloor

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

-
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

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

Code Snippets

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

Context

StackExchange Code Review Q#109569, answer score: 5

Revisions (0)

No revisions yet.