简体   繁体   中英

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.

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

只需使用字符数。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM