JavaScript Round To The Nearest 5

11th April 2009

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. function round5(x)
  2. {
  3. return (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
  4. }

Use the function like this:

  1. alert(round5(12)); // returns 10
  2. alert(round5(14)); // returns 15

Comments

Permalink
Thanks for the function, it really helped! Robert

Robert (Thu, 12/13/2012 - 16:56)

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

Chris (Fri, 06/27/2014 - 11:49)

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

Mark (Thu, 10/12/2017 - 09:42)

Permalink
Thanks!

Mike (Sat, 10/21/2017 - 16:46)

Add new comment

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