I want to write a function that given a number will set all but the first digit to zero and will increase the first digit by one
for example, 175 should become 200, 23 should become 30, etc. What is the best way to do this?
function truncUp(num) {
var factor = Math.pow(10, (num+'').toString().length - 1);
return Math.floor(num / factor) * factor + factor;
}
that was fun :D
And for the unnamed "others":
function truncUp(num) {
num = Math.floor(num);
var factor = Math.pow(10, (Math.abs(num)+'').toString().length - 1);
return Math.floor(num / factor) * factor + ((Math.abs(num) - num == 0?1:2)*factor);
}
function myRound(num)
{
var digits = String(num).length - 1,
pow = Math.pow(10, digits);
num /= pow;
num = Math.ceil(num);
num *= pow;
return num;
}
Short version:
function myRound(num)
{
var pow = Math.pow(10, String(num).length - 1);
return Math.ceil(num/pow)*pow;
}
Tests:
> myRound(175)
200
> myRound(23)
30
> myRound(95)
100
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