Forum Moderators: coopster

Message Too Old, No Replies

Rounding Numbers to the Next Highest 50

         

Frank_Rizzo

1:40 pm on Feb 22, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I can use the round(), ceiling() and floor() functions to make numbers upto the next whole number (3.6 -> 4 etc.) but how do I round a number to the next highest 50?

e.g.

36.3 -> 50
83.2 -> 100
-26.5 -> -50
-94.0 -> -100

TIA.

NickCoons

3:37 pm on Feb 22, 2005 (gmt 0)

10+ Year Member



You could try something like this:

$number = (ceil($number / 50)) * 50;

That would round 36.3 to 50, and 82.3 to 100.

Technically, -26.5 rounded "up" to the next highest 50 is 0, not -50; and -94 rounded "up" to the next highest 50 is -50, not -100. I believe that's how the above example would behave.

If you wanted to round negative numbers as you specified, you might want to do a test first to see if the number is negative or positive. If the latter, run the above. If the former, run a modified version of the above.

Frank_Rizzo

9:54 pm on Feb 22, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That way of using ceil worked a treat.

To make it work the way I want to with negative numbers I did this:

$number = -26.3;
$sign = ($number <0? -1 : 1);
$number = (ceil(abs($number) / 50)) * 50 * $sign;

result = -50

Cheers.