patterncsharpMinor
Floor and Ceiling to specified int
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?
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
For
If you don't want to think about or deal with negative numbers you should either change the signature to accept only
-
Just considering positive numbers
Less logic to read and verify in your head.
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 topublic 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.