CJS
CJS

Reputation: 351

Rounding to nearest 5/10 in PHP

I have two inputs

min, max

In the case where min=32 and max=46 then I would like PHP to automatically the value to the nearest 5/10 i.e. in this case min=30 and max=50?

But in the instance of course if min=35 or 40 and max=40 or 45 there would be no need to round off.

How do achieve this in PHP?

Btw the system only deals with integer values and the above values are just examples. It needs to work for a range of numbers ranging from 0 to infinity. So 4 would round to 0, 6 to 10... etc...

Upvotes: 0

Views: 1554

Answers (2)

kba
kba

Reputation: 19466

If you multiply the number by two, you can round this to 10s and then divide it by 2 again.

function round_five($num) {
    return round($num*2,-1)/2;
}

$nums = array(32,46,35,40);

foreach($nums as $num) {
    printf("%s: %s\n",$num,roundFive($num));
}

The above will return

32: 30
46: 45
35: 35
40: 40

Upvotes: 2

Dogbert
Dogbert

Reputation: 222188

function round_to_10($n) {
  return round($n / 10) * 10;
}


php> echo round_to_10(32)
30
php> echo round_to_10(46)
50

Upvotes: 6

Related Questions