Ekramul Hoque
Ekramul Hoque

Reputation: 5123

How can I round up a number without php function ceil

I'm trying to build a function that output will be rounded up number. I know there is a php function, but I want to make this function for another purpose.

Upvotes: 1

Views: 1682

Answers (5)

NappingRabbit
NappingRabbit

Reputation: 1918

you want ceil without using ceiling...

intval($number + .5)

this is the same thing, but you are still using a built in function.

EDIT: apparently the above solution does not work as I intended it to in PHP. You can use the round function to similar effect

round($number + .5)

or something similar to another answer:

$n = intval($number + .5);
if($n < $number){
    $n++;
}

Upvotes: 4

Devang Rathod
Devang Rathod

Reputation: 6736

You can use round() and floor() and number_format() for round up number.

echo round(153.751);     // 154
echo floor(153.751); // 153
echo number_format(153.751); // 154

Upvotes: 0

Sebastian Schmitt
Sebastian Schmitt

Reputation: 483

You could cut off the fractional part by casting it to an integer and afterwards check, whether the so derived value is smaller or even the initial value.

$input = 3.141592653;
$intVersion = (int) $input;
if($intVersion<$input) $intVersion++;
return $intVersion

Upvotes: 1

devBinnooh
devBinnooh

Reputation: 611

If you want to round up/down You can use round method

/* Using PHP_ROUND_HALF_UP with 1 decimal digit precision */
 echo round( 1.55, 1, PHP_ROUND_HALF_UP);   //  1.6
 echo round( 1.54, 1, PHP_ROUND_HALF_UP);   //  1.5
 echo round(-1.55, 1, PHP_ROUND_HALF_UP);   // -1.6
 echo round(-1.54, 1, PHP_ROUND_HALF_UP);   // -1.5

 /* Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision */
 echo round( 1.55, 1, PHP_ROUND_HALF_DOWN); //  1.5
 echo round( 1.54, 1, PHP_ROUND_HALF_DOWN); //  1.5
 echo round(-1.55, 1, PHP_ROUND_HALF_DOWN); // -1.5
 echo round(-1.54, 1, PHP_ROUND_HALF_DOWN); // -1.5

 /* Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision */
echo round( 1.55, 1, PHP_ROUND_HALF_EVEN); //  1.6
echo round( 1.54, 1, PHP_ROUND_HALF_EVEN); //  1.5
echo round(-1.55, 1, PHP_ROUND_HALF_EVEN); // -1.6
echo round(-1.54, 1, PHP_ROUND_HALF_EVEN); // -1.5

/* Using PHP_ROUND_HALF_ODD with 1 decimal digit precision */
echo round( 1.55, 1, PHP_ROUND_HALF_ODD);  //  1.5
echo round( 1.54, 1, PHP_ROUND_HALF_ODD);  //  1.5
echo round(-1.55, 1, PHP_ROUND_HALF_ODD);  // -1.5
echo round(-1.54, 1, PHP_ROUND_HALF_ODD);  // -1.5
?>

Note: ceil round up

Upvotes: 0

xManh
xManh

Reputation: 67

May this do it?

function newceil($num)
{
    $re=intval($num);
    if($re<$num) $re++;
    return $re
}

Upvotes: 1

Related Questions