Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript rounding function

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?

like image 473
trs Avatar asked May 25 '26 08:05

trs


2 Answers

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);
}
like image 62
Joseph Marikle Avatar answered May 27 '26 22:05

Joseph Marikle


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
like image 23
Matt Ball Avatar answered May 27 '26 21:05

Matt Ball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!