Keith
Keith

Reputation: 26499

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.

Upvotes: 0

Views: 7931

Answers (7)

rajatbarman
rajatbarman

Reputation: 149

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

This works for me :)

Upvotes: 1

ozhug
ozhug

Reputation: 1083

Something like this should work:

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

Upvotes: 0

mrtsherman
mrtsherman

Reputation: 39872

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?

Upvotes: 2

Yanick Rochon
Yanick Rochon

Reputation: 53526

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

Upvotes: 3

Populus
Populus

Reputation: 7680

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

Upvotes: 2

Josnidhin
Josnidhin

Reputation: 12504

Try the following

ceil($category_count/10)*10

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881303

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

Upvotes: 0

Related Questions