Re: Round to the nearest X - SOLVED
| From: | Chris Boget | Date: | Fri, 29 Apr 2005 13:20:57 +0000 |
| Subject: | Re: Round to the nearest X - SOLVED | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-214203@lists.php.net to get a copy of this message | ||
Thank you for everyone's suggestions. Using them
(and a few other things I've found elsewhere), I've
come up with the following function:
function roundToNearest( $number, $toNearest = 5 ) {
$retval = 0;
$mod = $number % $toNearest;
if( $mod >= 0 ) {
$retval = ( $mod > ( $toNearest / 2 )) ? $number + ( $toNearest - $mod )
: $number - $mod;
} else {
$retval = ( $mod > ( -$toNearest / 2 )) ? $number - $mod : $number +
( -$toNearest - $mod );
}
return $retval;
} // end function round();
that works with positive and negative numbers and seems
to work with every test I threw at it.
Thanks again for everyone's help!
thnx,
Chris