Reputation: 1454
I have different numbers in my code.
For example I want to 1466521
rounded up to 1500000
or 13422
rounded up to 14000
or 4387
rounded to 4400
How can I round up every number in php?
Upvotes: 1
Views: 99
Reputation: 489
Its very simple but logical task...use below code
function rounded_fun($num){
$num_length = strlen($num);
$devide_num = 1;
for($i=2;$i<$num_length;$i++){
$devide_num = $devide_num*10;
}
$rounded_num = ceil($num / $devide_num) * $devide_num;
return $rounded_num;
}
echo rounded_fun(1466521); //1500000
echo rounded_fun(13422); //14000
echo rounded_fun(4387); //4400
echo rounded_fun(12345); //13000
Upvotes: 1
Reputation: 573
You can use different method to acheive this logic.
You can use this function to make your logic but this will convert your number to string and will ultimately return a number.
function CustomRound($varNum) {
$varNum = (string)$varNum;
$len = strlen($varNum);
$varLastNum = (int)substr($varNum,2);
if($varLastNum>0) {
$varFirstTwoDigit = (int)substr($varNum,0,2);
$varFirstTwoDigit++;
return (int)str_pad($varFirstTwoDigit,$len,0);
}
return $varNum;
}
Second method is to check how many numbers are there after two digits and them multiply the first two digit with the number generated by pow(10, $strLength-2)
.
Upvotes: 0
Reputation: 7896
By using ceil you can achive your desired result.
if( !function_exists('ceiling') )
{
function ceiling($number, $significance = 1)
{
return ( is_numeric($number) && is_numeric($significance) ) ? (ceil($number/$significance)*$significance) : false;
}
}
$num = 4387;
$round = (strlen($num)-2);
$roundfraction = pow(10, $round);
echo ceiling($num, $roundfraction); //output 4400
for more detail have a look at http://php.net/manual/en/function.ceil.php
other alternative can be round function:
$num = 123456789;
echo round($num,0); // whole number - prints 123456789
echo round($num,-1); // ten - prints 123456790
echo round($num,-2); // hundred - prints 123456800
echo round($num,-3); // thousand - prints 123457000
echo round($num,-4); // ten thousand - prints 123460000
echo round($num,-5); // hundered thousand - prints 123500000
echo round($num,-6); // million - prints 123000000
echo round($num,-7); // ten million - prints 120000000
echo round($num,-8); // hundred million - prints 100000000
echo round($num,-9); // billion - prints 0
For general you can use belo solution:
$num = 1466521;
$round = (strlen($num)-2)*-1;
echo round($num,$round); // prints 1500000
Upvotes: 0
Reputation: 1
$num = '1454856';
$base= pow(10, strlen($num)-2);
echo ceil($num/$base) * $base;
Upvotes: 0
Reputation: 1436
You can try this:
$str = 4387; // 13422, 1466521
$len = pow(10,(strlen($str)-2)); // Here 2 present 2nd position of your digit. It will change according to your need.
$result = ceil($str/$len) * $len;
echo $result;
Upvotes: 0
Reputation:
Try this:
$str = '13422';
$ex = 1;
$ex = str_pad($ex, (strlen($str)-1), 0);
echo round(ceil($str/$ex), PHP_ROUND_HALF_UP) * $ex;
Upvotes: 0