简体   繁体   中英

Always rounding decimals up to specified precision

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;

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM