JavaScript Round To Nearest Number

11th April 2009

The JavaScript Math.round() function will round a decimal to the nearest whole number, but I found that I needed was to round a number to the nearest 10. So after a bit of thinking I realised that I could divide the value by 10, round it using the round() function and then multiply the result by 10.

So taking it a step further I decided to create a function that would round a number to the nearest 10, 100, 1000 or whatever value is entered. If this value is less than 0 then do the reverse by multiplying and dividing the number by the given value of accuracy. Here is the function.

  1. function roundNearest(num, acc){
  2. if ( acc < 0 ) {
  3. num *= acc;
  4. num = Math.round(num);
  5. num /= acc;
  6. return num;
  7. } else {
  8. num /= acc;
  9. num = Math.round(num);
  10. num *= acc;
  11. return num;
  12. }
  13. }

Here are some tests of the function.

  1. alert( roundNearest(12345, 1000) ); // 1200
  2. alert( roundNearest(12345.1234, -100) ); //12345.12

This function can be simplified a little by putting all of the calculations onto one line.

  1. function roundNearest(num, acc){
  2. if ( acc < 0 ) {
  3. return Math.round(num*acc)/acc;
  4. } else {
  5. return Math.round(num/acc)*acc;
  6. }
  7. }

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.