Round number to nearest thousand, up or down depending on the number

By using ES3 Number method, it performs a rounding if no decimal place defined.

(value / 1000).toFixed() * 1000




The original answer was:
(value / 1000).toFixed(3) * 1000;

Yet this is incorrect, due to the value will return the exact original number, instead of affecting the ceil/floor on the value.


var rest = number % 1000; 
if(rest > 500) 
{ number = number - rest + 1000; } 
  else 
{ number = number - rest; } 

maybe a bit straight forward.. but this does it

EDIT: of course this should go in some kind of myRound() function

I read about the problem with your 1 needing to round up to 1000. this behaviour is controverse compared to the rest - so you will have to add something like:

if(number < 1000)
{  number = 1000; return number; }

ontop of your function;


This will do what you want:

Math.round(value/1000)*1000

examples:

Math.round(1001/1000)*1000
1000
Math.round(1004/1000)*1000
1000
Math.round(1500/1000)*1000
2000

So this function below allow you to roundUp a number to the nearest near, basically you can roundUp a number to the nearest 10, or 1000 by just passing near 10,1000. That is all.

For instance, if i want to roundUp 10 to nearest 10, it should not return 20 as in the accepted answer, it should return 10.

function roundUp(number,near){
  if(number%near===0) return number;
    return  parseInt(number / near) * near+near;
  
}

console.log(roundUp(110,10)) // 110
console.log(roundUp(115,10)) // 120
console.log(roundUp(115,100)) // 200

Tags:

Javascript