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.
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 .
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
const roundup = n => 10 ** ("" + n).length
Just use the number of characters.
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));
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));
//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
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