2

I'm looking for an elegant way to rounding up decimal numbers always up. Seems like round(0.0045001, 5, PHP_ROUND_HALF_UP); is not returning what I expected so I came up with following function;

function roundUp($number, $precision) {
    $rounded = round($number, $precision);

    if ($rounded < $number) {
        $add = '0';
        for ($i = 1; $i <= $precision; $i++) {
            if ($i == 1) $add = '.';
            $add .= ($i == $precision) ? '1' : '0';
        }
        $add = (float) $add;
        $rounded = $rounded + $add;
    }

    return $rounded;
}

I was wondering if there is any other, more elegant way to achieve this?

Expected Result : var_dump(roundUp(0.0045001, 5)) // 0.00451;

Revenant
  • 2,942
  • 7
  • 30
  • 52

3 Answers3

4
function roundup_prec($in,$prec)
{
    $fact = pow(10,$prec);
    return ceil($fact*$in)/$fact;
}

echo roundup_prec(0.00450001,4)."\n";
echo roundup_prec(0.00450001,5);

gives:

0.0046
0.00451
mvds
  • 45,755
  • 8
  • 102
  • 111
  • I don't know why I used it with `pow()` but couldn't get the correct result. I guess I did some mistake which I didn't notice. Thanks a lot. – Revenant Jan 07 '12 at 18:22
0
function roundUp($number, $precision) {
    $rounded = round($number, $precision);

    if ($rounded < $number) {
        $add = '0';
        for ($i = 1; $i <= $precision; $i++) {
            if ($i == 1) $add = '.';
            $add .= ($i == $precision) ? '1' : '0';
        }
        $add = (float) $add;
        $rounded = $rounded + $add;
    }

    return ceil($rounded);
}
BoqBoq
  • 4,564
  • 5
  • 23
  • 29
  • if I wanted to use ceil, I wouldn't go through all these trouble and just use `ceil(0.0045001)` right? Thanks for the effort though. – Revenant Jan 07 '12 at 18:14
0

Instead of ceil(x) you can also use (int)x, which gives the same result

EDIT: OK forget about that, I meant (int)x + 1 and thats not true for a number that's already rounded.

v01pe
  • 1,096
  • 2
  • 11
  • 19