[英]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. 我知道有一个php函数,但我想将此函数用于其他目的。
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. 编辑:显然上述解决方案无法按照我的意图在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++;
}
May this do it? 这样可以吗?
function newceil($num)
{
$re=intval($num);
if($re<$num) $re++;
return $re
}
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
If you want to round up/down You can use round
method 如果要向上/向下取整,可以使用取round
方法
/* 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 注意:ceil向上取整
You can use round()
and floor()
and number_format()
for round up number. 您可以使用round()
和floor()
以及number_format()
来取整数字。
echo round(153.751); // 154
echo floor(153.751); // 153
echo number_format(153.751); // 154
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.