Home > JavaScript > JavaScript Round To The Nearest 5

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

Categories: JavaScript Tags: , , , ,
  1. William Lockwood
    December 24th, 2009 at 18:00 | #1

    I haven’t been able to come up with a better way of doing this on my own - do you mind if I use this function?

  1. No trackbacks yet.