Saturday, 4 April 2009

Extended floor and ceil functions

I do not remember why i done this. Maybe this was used somewhere. Maybe i had practised in algorithms simply. Do not remember. There are two functions allowing round fractions down/up accordingly divider.
/**
 * Returns the lowest integer below $value divisible by divider
 *
 * @param  numeric $value Numeric value
 * @param  integer $div   Optional, divisor
 * @return numeric
 */
function boundFloor($value, $div=5)
{
    if ( $div < 2 ) {
        $div = 5;
    }

    $r = $value % $div;
    return floor($value - $r);
}

/**
 * Returns the highest integer above $value divisible by divider
 *
 * @param  numeric $value Numeric value
 * @param  integer $div   Optional, divider
 * @return numeric
 */
function boundCeil($value, $div=5)
{
    if ( $div < 2 ) {
        $div = 5;
    }

    $r = ($value + $div) % $div;
    return ceil($value + $div - $r);
}

/**
 * Example
 */
$x = range(0, 20);
$div = 10;
foreach ($x as $v) {
    printf("% 3d - % 3d % 3d\n", $v, boundFloor($v, $div), boundCeil($v, $div));
}

No comments:

Post a Comment