Reputation: 2984
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;
Upvotes: 2
Views: 1080
Reputation: 1136
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.
Upvotes: 0
Reputation: 47034
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
Upvotes: 4
Reputation: 4704
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);
}
Upvotes: 0