# js 如何向上取整得到距离最近的整十，整百，整千，整万的值？

## 回答

``````function ceilNumber(number){
var bite = 0;
if(number < 10){
return 10;
}
while( number >= 10 ){
number /= 10;
bite += 1;
}
return Math.ceil(number) * Math.pow(10,bite);
}``````
`````` function setCeil(value){
if (value < 10) {
return 10
} else {
let num = Number(value.toString().substring(0,1));
return (num + 1) * Math.pow(10,(value.toString().length - 1));
}
}``````

``````function upTo(v, steps) {
const step = steps.find(step => step > v);
const mod = v % step;
return mod ? v - mod + step : v;
}

const steps = [10, 20, 50, 100, 200, 500, 1000];
const nums = [6, 16, 66, 166, 666];

nums.forEach(n => console.log(upTo(n, steps)));

// 输出
// 10  20  100  200  1000``````
``````function dada(value) {
const array = Array.from(`\${ value }`);
const [_, ...behinds] = array;
if(array.length < 2) {
return 10;
}
else if(behinds.every(i => i === '0')) {
return value;
}
else {
return Number.parseInt(array.map((char, index) => index === 0 ? Number.parseInt(char) + 1 : 0).join(''));
}
}``````
``````[1, 11, 10, 20, 21, 211, 166, 311].forEach(value => {
console.log(`\${ value }: \${ dada(value) }`);
});``````
``````function ceilNum(num){
const bite = Math.pow(10,String(num).length-1||1)
return Math.ceil(num/bite)*bite
}
function test(){
const nums = [6, 16, 66, 166, 666];
nums.forEach(n => console.log(ceilNum(n)));
}
test()``````