JavaScript: Count the digits of an integer
JavaScript Math: Exercise-41 with Solution
Write a JavaScript function to count integer digits.
Sample Solution:-
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript function to count the digits of an integer.</title>
</head>
<body>
</body>
</html>
JavaScript Code:
function digits_count(n) {
var count = 0;
if (n >= 1) ++count;
while (n / 10 >= 1) {
n /= 10;
++count;
}
return count;
}
console.log(digits_count(12112));
console.log(digits_count(457));
Sample Output:
5 3
Flowchart:

Live Demo:
See the Pen javascript-math-exercise-41 by w3resource (@w3resource) on CodePen.
Contribute your code and comments through Disqus.
Previous: Write a JavaScript function to create random background color.
Next: Write a JavaScript function to calculate the combination of n and r.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join