JavaScript Round To The Nearest 5

I have already talked about a JavaScript function that rounds To the nearest number, but this was only useful if the number needed to be to the nearest 10 (or factor of). The following function is similar, but will round the number to the nearest 5 or 10, depending which is closer.

function round5(x)
{
    return (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
}

Use the function like this:

alert(round5(12)); // returns 10
alert(round5(14)); // returns 15

Comments

Thanks for the function, it really helped! Robert
Would it not be simpler to do:function round5(x) { return Math.round(x / 5) * 5; }
Hi thanks for the method!! it really help me !!
Thanks!

Thanks

//  Round to the nearest m multiple
//  USAGE: roundN(32, 5) => 30 (the nearest five)
//  USAGE: roundN(33, 5) => 35 (the nearest five)
function roundN(x, m)
{
    //  if (1 == m) return Math.round(x);
    return ((x % m) >= (m / 2))
    //  round up
    ? m * Math.round((x + (m / 2)) / m)
    //  round down
    :    m * Math.round(x / m);
}

 

Add new comment

The content of this field is kept private and will not be shown publicly.