tags:

views:

588

answers:

7

How can i round to nearest 10 in php? Say i have 23, what code would i use to get it to 30?

+4  A: 

div by 10 then use ceil then mult by 10

http://php.net/manual/en/function.ceil.php

John Nolan
A: 

We can "cheat" via round with

$rounded = round($roundee / 10) * 10;

We can also avoid going through floating point division with

function roundToTen($roundee)
{
  $r = $roundee % 10;
  return ($r <= 5) : $roundee - $r : $roundee + (10 - $r);
}

Edit: I didn't know (and it's not well documented on the site) that round now supports "negative" precision, so you can more easily use

$round = round($roundee, -1);

Edit again: If you always want to round up, you can try

function roundUpToTen($roundee)
{
  $r = $roundee % 10;
  if ($r == 0)
    return $roundee;
  return $roundee + 10 - $r;    
}
Adam Wright
hi, this works perfectly - for that question, how can i round UP? so 23 to 30?
tarnfeld
+9  A: 
round($number, -1);

This will round $number to the nearest 10. You can also pass a third variable if necessary to change the rounding mode.

More info here: http://php.net/manual/en/function.round.php

TallGreenTree
round isn't what he wants
John Nolan
I suppose people can't read, which is why this was voted up so many times.
Homework
Can you blame them for assuming the questioner meant "round to the nearest 10" when the question said "round to the nearest 10" twice?
ceejayoz
This answer was posted before the questioner clarified himself. I just figured he wasn't rounding correctly in the question.
TallGreenTree
+1  A: 

Try

round(23, -1);

Artyom Sokolov
A: 

My first impulse was to google for "php math" and I discovered that there's a core math library function called "round()" that likely is what you want.

Berry
+7  A: 

floor will go down.

ceil will go up.

round will go to nearest.

$number = floor($input / 10) * 10;

Daren Schwenke
ceil - that works :D!!!
tarnfeld
A: 

ceil($roundee / 10) * 10;

tarnfeld