How to round up integer in PHP?

柔情痞子 提交于 2019-12-11 17:16:38

问题


I want to round up any an integer to the next tens place number.

Some examples to illustrate my point:

-- I have the number 1, I would like this rounded up to 10

-- I have the number 35, I would like this rounded up to 40

-- I have the number 72, I would like this rounded up to 80

-- etc etc

// $category_count's value is 38
for($i = 1; $i <= $category_count; $i++) 
{ 
       if($i % 10 == 0)
       {
          echo "<a href=\"?page=$i\">$i;</a>"; 
       }
    }

The above code outputs 3 links, I need the fourth too.


回答1:


Your for is ineffective. If you need to modulus 10 your counter, use this code instead :

for($i = 1, $c = ceil($category_count/10); $i <= $c; $i++) 
{ 
    $j = $i * 10;
    echo "<a href=\"?page=$j\">$j;</a>"; 
}



回答2:


mrtsherman is almost right but OP's question needed it to round UP (1 => 10)

// $category_count's value is 38
$loop_limit = ceil($category_count/10);
for ($i = 1; $i <= $loop_limit; $i++) {
  $page = $i * 10;
  echo "<a href=\"?page={$page}\">{$page}</a>";
}



回答3:


Edited my answer to point to this question instead. Basically same thing with many good answers.

How to round up a number to nearest 10?




回答4:


round(($num/10))*10; // Make sure num is an integer or use (int) to convert string to integer.

This works for me :)




回答5:


One way to do this is to add 9, then truncate it at the tens place (integer divide by ten, then multiply by ten).

Alternatively, you can add 5 then use the round function with a negative precision:

echo round ($i + 5, -1);



回答6:


Try the following

ceil($category_count/10)*10



回答7:


Something like this should work:

(int(i/10) + 1) x 10


来源:https://stackoverflow.com/questions/7884550/how-to-round-up-integer-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!