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.
There are many anwers in this question, probably all will give you the answer you are looking for. But as @TallGreenTree mentions, there is a function for this.
But the problem of the answer of @TallGreenTree is that it doesn't round up, it rounds to the nearest 10. To solve this, add +5 to your number in order to round up. If you want to round down, do -5.
So in code:
round($num + 5, -1);
You can't use the round mode for rounding up, because that only rounds up fractions and not whole numbers.
If you want to round up to the nearest 100, you shoud use +50.
I was actually searching for a function that could round to the nearest variable, and this page kept coming up in my searches. So when I finally ended up writing the function myself, I thought I would post it here for others to find.
The function will round to the nearest variable:
function roundToTheNearestAnything($value, $roundTo)
{
$mod = $value%$roundTo;
return $value+($mod<($roundTo/2)?-$mod:$roundTo-$mod);
}
For people who want to do it with raw SQL, without using php, java, python etc.
SET SQL_SAFE_UPDATES = 0;
UPDATE db.table SET value=ceil(value/10)*10 where value not like '%0';
I wanted to round up to the next number in the largest digits place (is there a name for that?), so I made the following function (in php):
//Get the max value to use in a graph scale axis,
//given the max value in the graph
function getMaxScale($maxVal) {
$maxInt = ceil($maxVal);
$numDigits = strlen((string)$maxInt)-1; //this makes 2150->3000 instead of 10000
$dividend = pow(10,$numDigits);
$maxScale= ceil($maxInt/ $dividend) * $dividend;
return $maxScale;
}
Hey i modify Kenny answer and custom it not always round function now it can be ceil and floor function
function roundToTheNearestAnything($value, $roundTo,$type='round')
{
$mod = $value%$roundTo;
if($type=='round'){
return $value+($mod<($roundTo/2)?-$mod:$roundTo-$mod);
}elseif($type=='floor'){
return $value+($mod<($roundTo/2)?-$mod:-$mod);
}elseif($type=='ceil'){
return $value+($mod<($roundTo/2)?$roundTo-$mod:$roundTo-$mod);
}
}
echo roundToTheNearestAnything(1872,25,'floor'); // 1850<br>
echo roundToTheNearestAnything(1872,25,'ceil'); // 1875<br>
echo roundToTheNearestAnything(1872,25,'round'); // 1875