
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Round number down to nearest power of 10 JavaScript
We are required to write a JavaScript function that takes in a number. The function should return a power of 10 which is nearest to the input number.
For example −
f(1) = 1 f(5) = 1 f(15) = 10 f(43) = 10 f(456) = 100 f(999) = 100
Example
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));
Output
And the output in the console will be −
1000 100 1000
- Related Articles
- Nearest power 2 of a number - JavaScript
- How to round down to nearest integer in MySQL?
- $231546 \div 45$ round off to nearest 10.
- How to round the decimal number to the nearest tenth in JavaScript?
- How can I round down a number in JavaScript?
- Round a number to the nearest even number in C#
- How to round up to the nearest N in JavaScript
- Round off the following number to the nearest hundred:236
- Round off the following number to the nearest tens. 7896.
- Mean of an array rounded down to nearest integer in JavaScript
- Rounding off numbers to some nearest power in JavaScript
- Round off 1120 to nearest hundred.
- How to round off to nearest thousands?
- Nearest Prime to a number - JavaScript
- Round off to the nearest thousand.$5914$

Advertisements