Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round up number to nearest 100/1000 depending on number, in JavaScript?

I have a number that can be in the 2 digits, like 67, 24, 82, or in the 3 digits, like 556, 955, 865, or 4 digits and so on. How can I round up the number to the nearest n+1 digits depending on the number?

Example:

roundup(87) => 100,
roundup(776) => 1000,
roudnup(2333) => 10000

and so on.

like image 204
mikasa Avatar asked Jul 04 '18 08:07

mikasa


People also ask

How do you round a number to the nearest 100 in JavaScript?

To round a number to the nearest 100, call the Math. round() function, passing it the number divided by 100 and then multiply the result by 100 , e.g. Math. round(num / 100) * 100 .


5 Answers

You could take the logarithm of ten and round up the value for getting the value.

function roundup(v) {
    return Math.pow(10, Math.ceil(Math.log10(v)));
}

console.log(roundup(87));   //   100
console.log(roundup(776));  //  1000
console.log(roundup(2333)); // 10000

For negative numbers, you might save the sign by taking the result of the check as factor or take a negative one. Then an absolute value is necessary, because logarithm works only with positive numbers.

function roundup(v) {
    return (v >= 0 || -1) * Math.pow(10, 1 + Math.floor(Math.log10(Math.abs(v))));
}

console.log(roundup(87));    //    100
console.log(roundup(-87));   //   -100
console.log(roundup(776));   //   1000
console.log(roundup(-776));  //  -1000
console.log(roundup(2333));  //  10000
console.log(roundup(-2333)); // -10000
like image 149
Nina Scholz Avatar answered Oct 11 '22 04:10

Nina Scholz


 const roundup = n => 10 ** ("" + n).length

Just use the number of characters.

like image 26
Jonas Wilms Avatar answered Oct 11 '22 03:10

Jonas Wilms


You can check how many digits are in the number and use exponentiation:

const roundup = num => 10 ** String(num).length;
console.log(roundup(87));
console.log(roundup(776));
console.log(roundup(2333));
like image 5
CertainPerformance Avatar answered Oct 11 '22 03:10

CertainPerformance


You can use String#repeat combined with Number#toString in order to achieve that :

const roundUp = number => +('1'+'0'.repeat(number.toString().length));

console.log(roundUp(30));
console.log(roundUp(300));
console.log(roundUp(3000));
like image 4
Zenoo Avatar answered Oct 11 '22 03:10

Zenoo


//Math.pow(10,(value+"").length)   


console.log(Math.pow(10,(525+"").length))
console.log(Math.pow(10,(5255+"").length))

I came up with another solution that does'nt require a new function to be created

like image 3
Bilal Alam Avatar answered Oct 11 '22 03:10

Bilal Alam