How can i round to nearest 10 in php? Say i have 23, what code would i use to get it to 30?
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
2009-10-24 22:01:38
hi, this works perfectly - for that question, how can i round UP? so 23 to 30?
tarnfeld
2009-10-24 22:05:43
+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
2009-10-24 22:02:00
I suppose people can't read, which is why this was voted up so many times.
Homework
2009-10-24 22:57:42
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
2009-10-26 01:20:39
This answer was posted before the questioner clarified himself. I just figured he wasn't rounding correctly in the question.
TallGreenTree
2009-10-26 13:56:10
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
2009-10-24 22:03:22
+7
A:
floor will go down.
ceil will go up.
round will go to nearest.
$number = floor($input / 10) * 10;
Daren Schwenke
2009-10-24 22:03:38