简体   繁体   中英

How to round up integer in PHP?

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.

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>"; 
}

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?

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>";
}
round(($num/10))*10; // Make sure num is an integer or use (int) to convert string to integer.

这对我有用:)

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);

这样的事情应该起作用:

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

尝试以下

ceil($category_count/10)*10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM