how can I round to a multiple of a number in javascript?

javascript, jquery

Solution

You can use a simple function like this:

function roundMultiple3(num) {
  return(Math.round(num / 3) * 3);
}

This divides by 3, rounds to the nearest integer, then multiplies by 3 again to restore the full value.

Or a generic version that allows you to specify the multiple:

function roundMultiple(num, multiple) {
  return(Math.round(num / multiple) * multiple);
}

Problem

While I understand the Math.round/ceil/floor functions in javascript, I have been unable to come up with a working function to this problem. What I want to do is round any whole number to a multiple of 3, or in fact any multiple which I choose. The requirements of the returned numbers when the the multiple value of '3' is given are as follows: ``` 0 returns 0 6 returns 6 7 returns 6 8 returns 9 22 returns 21 23 returns 24 ``` etc..etc... So basically, the returned value will always be a multiple of the given parameter, in this case '3'. Thanks all.

Original source