เราต้องเขียนฟังก์ชันที่รับตัวเลขและคืนกำลังของ 10 ที่ใกล้ที่สุด (ปัดลง)
ตัวอย่าง: f(1)=1, f(5)=1, f(15)=10, f(43)=10, f(456)=100, f(999)=100
ตัวอย่างโค้ด
const num = 2355;
const num1 = 346;
const num2 = 678;
const nearestPowerOfTen = (num) => {
let count = 0;
while (num > 1) { count++; num /= 10; }
return Math.pow(10, count - 1) * (Math.round(num) ? 10 : 1);
};
console.log(nearestPowerOfTen(num));
console.log(nearestPowerOfTen(num1));
console.log(nearestPowerOfTen(num2));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
1000 100 1000