w3resource

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:

Flowchart: JavaScript Math- Count the digits of an integer

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.



Follow us on Facebook and Twitter for latest update.