I want to round up a number to the nearest thousand, at the moment I'm using this:
Math.ceil(value/1000)*1000;
But this goes always up, if I type 1001 it will go to 2000, I want to go up or down depeding on the number, for example 1001 goes to 1000 or 1400 goes to 1000 but 1500 goes to 2000
EDIT:
if(value<1000){
value = 1000;
}else{
value = Math.round(value/1000)*1000;
}
So we round 1500 up to 2000. Since we are rounding to the nearest thousand, we look at the digit in the hundreds place. The digit in the hundreds place is 4. So we round 1499 down to 1000.
What is 52437 rounded to the nearest thousand? Rounding 52437 to the nearest thousand will make the number into 52000 .
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
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;
By using ES3 Number method, it performs a rounding if no decimal place defined.
(value / 1000).toFixed() * 1000
(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.
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
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With