Re: How to Round to the Nearest Multiple of 50?
| From: | Lars Torben Wilson | Date: | Thu, 14 Sep 2000 06:17:40 +0000 |
| Subject: | Re: How to Round to the Nearest Multiple of 50? | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-16720@lists.php.net to get a copy of this message | ||
Richard Creech writes:
> Hello All,
> I have an integer variable - lets call it $scaleHeight - somewhere
> between 0 and 1200. In all likelihood this variable will not be a
> multiple of 50. It will be 49 or 51 or 1143 or 856 ...
>
> How do I round $scaleHeight to the Nearest Multiple of 50?
>
> The reason I wish to do this is to obtain a variable which I can
> then use in a switch statement, which is clearer to code and faster
> to run than a whole lot of if statements.
>
>
> Anyone know the answer?
>
> Regards,
>
> Richard Creech
> richardc@dreamriver.com Phone: 250.744.3350 Pacific Time Canada
> Download phpYellow Pages 2000 - BETA
> Add Dynamic Database Content to your Website
> http://www.dreamriver.com/software/
I think I'd do something like this:
<?php
error_reporting(E_ALL);
/* Rounds up. */
function round_to_nearest($num, $round_to) {
$mod = $num % $round_to;
return $mod >= (int) ($round_to / 2) ? $num + ($round_to - $mod) : $num - $mod;
}
/* Test it */
mt_srand((double) (microtime() * 1000000));
for ($i = 0; $i < 15; $i++) {
$num = mt_rand(1, 1200);
$nearest = round_to_nearest($num, 50);
echo "Nearest 50 to $num is $nearest.\n";
}
?>
Hope this helps,
Torben
--
+----------------------------------------------------------------+
|Torben Wilson <torben@php.net> Netmill iTech|
|http://www.coastnet.com/~torben http://www.netmill.fi|
|Ph: 1 250 383-9735 torben@netmill.fi|
+----------------------------------------------------------------+