JavaScript Round To The Nearest 5

Saturday, April 11, 2009 - 22:50

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.

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

Use the function like this:

1
2
alert(round5(12)); // returns 10
alert(round5(14)); // returns 15
Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

Thanks for the function, it really helped!

Robert

Hi thanks for the method!! it really help me !!

Would it not be simpler to do:
1
2
3
function round5(x) {
    return Math.round(x / 5) * 5;
}

Thanks!

Add new comment