Cut-N-Paste Corner: PHP function – Dynamically Round up to nearest 10, 100, 1000 or whatever (Graphing Axis Sex Toy)
One from the "Random-Shit-Pulled-Out-of-the-Junk-Drawer" Department... as I sit here and watch my beloved Red Sox cement their way OUT of playoffs... {sigh}
Here's a little function I use when building sexy little graphs in my PHP Reporting / Web Interfaces. Its good to calculate a MAX value for the graph axis. Since we never know what the values are going to be until we coax that data out of the DB - it could be 10, could be 10,000 or 10,000,000 (sometimes its even "apple", but fruit to integer conversions will be another day)
// $biggs would be the biggest num in your set
// (assuming a "max" value graph-building situation
function RoundUptoNearestN($biggs){
$rounders = (strlen($biggs)-2) * -1;
$places = strlen($biggs)-2;
$counter = 0;
while ($counter <= $places) {
$counter++;
if($counter==1) {
$holder = $holder.'1'; }
else {
$holder = $holder.'0'; }
}
$biggs = $biggs + $holder;
$biggs = round($biggs, $rounders);
if($biggs<100) {
if($biggs<100) { $biggs = 100; }
else { $biggs = 100; }
}
return $biggs;
}
//Usage:
echo '<pre>';
echo RoundUptoNearestN(1424)."\n"; //returns 1500
echo RoundUptoNearestN(123)."\n"; //returns 130
echo RoundUptoNearestN(154368)."\n"; //returns 160000
echo RoundUptoNearestN(12334)."\n"; //returns 13000
echo RoundUptoNearestN(75)."\n"; //returns 100
echo '</pre>';
///etc etc etc :P
?>
I'm sure there is a WAY more elegant way to do this using the CEIL function, but for my needs - this fit the bill and I couldn't find anything out there on the interwebs that worked exactly like I wanted for this purpose (aka "I never want to round down, and still need to keep it close to the original number").
If you were wondering about the "sexy little graph" thing I mentioned - check out Open Flash Chart, its quick, pretty and just-plain-works.
If anyone wants to correct me with a ONE LINE version to embarrass me - go for it! But remember:
- It doesn't mean that I'm wrong
- It won't add inches to your dick
- Those Mountain Dew Rumors might be true
- EVERYONE can see your bald spot - stop living a lie!
I keed! I keed! :)