Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round up to nearest multiple of five in PHP

I want a php function which returns 55 when calling it with 52.

I've tried the round() function:

echo round(94, -1); // 90 

It returns 90 but I want 95.

Thanks.

like image 949
ahmadbrkat Avatar asked Nov 09 '10 12:11

ahmadbrkat


People also ask

How do you round up to multiples of 5?

If you need to round a number to the nearest multiple of 5, you can use the MROUND function and supply 5 for number of digits. The value in B6 is 17 and the result is 15 since 15 is the nearest multiple of 5 to 17.

How do I round up in PHP?

The ceil() function rounds a number UP to the nearest integer, if necessary. Tip: To round a number DOWN to the nearest integer, look at the floor() function. Tip: To round a floating-point number, look at the round() function.

How do you round to the nearest 5th?

To round to the nearest 5, you can simply use the MROUND Function with multiple = 5. By changing 5 to 50, you can round to the nearest 50 or you can use .

How do you round to the nearest multiple?

You can use CEILING to round prices, times, instrument readings or any other numeric value. CEILING rounds up using the multiple supplied. You can use the MROUND function to round to the nearest multiple and the FLOOR function to round down to a multiple.


2 Answers

This can be accomplished in a number of ways, depending on your preferred rounding convention:

1. Round to the next multiple of 5, exclude the current number

Behaviour: 50 outputs 55, 52 outputs 55

function roundUpToAny($n,$x=5) {     return round(($n+$x/2)/$x)*$x; } 

2. Round to the nearest multiple of 5, include the current number

Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 50

function roundUpToAny($n,$x=5) {     return (round($n)%$x === 0) ? round($n) : round(($n+$x/2)/$x)*$x; } 

3. Round up to an integer, then to the nearest multiple of 5

Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 55

function roundUpToAny($n,$x=5) {     return (ceil($n)%$x === 0) ? ceil($n) : round(($n+$x/2)/$x)*$x; } 
like image 125
SW4 Avatar answered Sep 20 '22 09:09

SW4


  1. Divide by 5
  2. round() (or ceil() if you want to round up always)
  3. Multiply by 5.

The value 5 (the resolution / granularity) can be anything — replaced it in both step 1 and 3

So in summary:

    $rounded_number = ceil( $initial_number / 5 ) * 5 
like image 42
jensgram Avatar answered Sep 19 '22 09:09

jensgram