How to usea While Loop and Integer Division in Javascript
In this approach, we repeatedly divide the number by 10 until it becomes 0. We count the number of divisions performed which corresponds to the number of digits in the original number.
Example: Here, we have used while loop and integer division to Count Digits of a Given Number.
function countDigits(number) {
let count = 0;
while (number !== 0) {
number = Math.floor(number / 10);
count++;
}
return count;
}
// Example
const number = 123456;
console.log("Number of digits:", countDigits(number));
Output
Number of digits: 6
JavaScript Program to Count Digits of a Given Number
Count Digits of a Given Number refers to determining the total number of individual digits present in a given numerical value. This involves analyzing each digit within the number and calculating how many digits are present in total.
Examples:
Input : 12345 Output : Total number of digits in 12345 is : 5 Input : 64674345 Output : Total number of digits in 12345 is : 8
There are several methods that can be used to Count Digits of a Given Number:
Table of Content
- Using a Reduce Method
- Using for Loop
- Using String Conversion
- Using Math Log10
- Using Recursion
- Using a While Loop and Integer Division