Round number to nearest thousand, up or down depending on the number
Solution 1:
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
Solution 2:
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;
Solution 3:
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
Solution 4:
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.
Solution 5:
Not the exactly point, but to round a number like 1250 to 1.2k or 55730 to 55,7m you might use something like:
let value = 90731+'';
let len = value.length;
let sym = len>6?'m':'k';
let hundred = (len==9||len==6);
if(len>3){
value = value.slice(0,-3)+(hundred?'':'.'+value.charAt(1))+sym;
};