Jump to content

[SOLVED] Rounding an Integer


pacchiee

Recommended Posts

<?php
function roundnum ($num, $nearest)
{
   $ret = 0;
   $mod = $num % $nearest;

   if ($mod >= 0)
     $ret = ( $mod > ( $nearest / 2)) ? $num + ( $nearest - $mod) : $num - $mod;
    else
     $ret = ( $mod > (-$nearest / 2)) ? $num - $mod : $num + ( -$nearest - $mod);
    return $ret;
}

echo roundnum (1234, 15);  // round to the nearest 15
echo roundnum (1234, 5); // round to the nearest 5
?>

 

http://www.markblah.com/2008/05/11/php-round-number-to-nearest-x/

  Quote

Hello nbarone,

 

Thanks. That function rounds an integer to the nearest specified SINGLE number. But I want to round an integer to its nearest 5 or 10 BOTH.

 

Sorry, I guess I don't quite understand what you're trying to accomplish, this function rounds to the nearest 5.

Maybe this is what you were looking for....it takes decimal into account...prolly not the most efficient way, but it works:

 

<?php
function roundnum ($num, $nearest)
{
   $ret = 0;
   $mod = $num % $nearest;

   if ($mod >= 0)
     $ret = ( $mod > ( $nearest / 2)) ? $num + ( $nearest - $mod) : $num - $mod;
    else
     $ret = ( $mod > (-$nearest / 2)) ? $num - $mod : $num + ( -$nearest - $mod);

 $dec_check = explode(".",$ret);
 if($dec_check[1]){
 	$tenth = $dec_check[1];
	if($tenth > 4){
		$ret = $ret+$nearest;
	}
}
    return floor($ret);
}

echo roundnum (17.5, 5); // = 20
echo roundnum (17.4, 5); // = 15
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.