0

I want a function that does

NearestFive(3) --> 5
NearestFive(5) --> 0
NearestFive(6) --> 5

if that makes sense. Best I can come up with is

function NearestFive ( x )
{
   var r = x % 5; 
   if ( r == 0 ) return x; 
   else if ( r > 2 ) return x + 5 - r;
   else return x - r;
}

but I'm wondering if it's possible to consolidate those steps or introduce bitshift operations to add efficiency?

For example, running two comparisons

  1. r == 0
  2. r > 2

may not be necessary since r > 2 implies r == 0.

Subpar Web Dev
  • 3,210
  • 7
  • 21
  • 35
  • 5
    Did you search at all, there seems to be [this answer](http://stackoverflow.com/questions/18953384/javascript-round-up-to-the-next-multiple-of-5) and [this answer](http://stackoverflow.com/questions/10535817/javascript-round-up-and-down-to-the-nearest-5-then-find-a-common-denominator) and several others that show different ways of doing this, surely some of them must be efficient enough ? – adeneo Apr 15 '16 at 18:47
  • For integers only as shown in your example code? – Yogi Apr 15 '16 at 19:17
  • `return ((x+2) / 5) * 5;` – user3386109 Apr 15 '16 at 19:21
  • Is the second example a mistake? `5 -> 0` or `5 -> 5`? – trincot Apr 16 '16 at 23:18

2 Answers2

5

The trivial way to "round to the nearest X" is to divide by X, round to the nearest integer, then multiply by X again.

function NearestX(num, factor) {
    return Math.round(num/factor)*factor;
}

This even works for rounding to the nearest fractional part (eg. nearest 0.1)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

Depending on your browser this could run fast:

function NearestFive5 ( x )
{
   return (((x+2)/5)>>0) * 5;
}

In my browser performance is equal with Math.round(x/5)*5, but both are notably faster than the version you posted in the question.

trincot
  • 317,000
  • 35
  • 244
  • 286