0

I'm trying to count the digits of a number and I found this function

function countDigits(y){
  num = parseInt(y)
  count = 0
  if (num >= 1)
    ++count;

  while (num / 10 >= 1) {
    num /= 10;
    ++count;
  }
  
  return count;
}

console.log(countDigits("123456"));
console.log(countDigits("1"));
console.log(countDigits("012"));

I'm taking the input from a string digit y.

The problem with the function is when a number starts with a zero it doesn't count it?

5
  • What is the type of y? Commented Feb 22, 2021 at 5:38
  • Numbers can't start with a 0 (not including numbers between -1 and 1) Commented Feb 22, 2021 at 5:39
  • y is a string and I have to validate a phone number that is why I need the zero to be counted Commented Feb 22, 2021 at 5:40
  • @beans in that case, why not just get the length of the string (y.length)? Commented Feb 22, 2021 at 5:45
  • I needed to make sure they are all numbers too Commented Feb 22, 2021 at 5:48

2 Answers 2

4

parseInt will ignore leading zeroes. You need something like:

function countDigitsInANumericString(numeric) {
  return numeric.split('').filter((n) => Number.isFinite(parseInt(n))).length;
}

console.log(countDigitsInANumericString('0a1023')); // 5

console.log(countDigitsInANumericString('0123')); // 4

console.log(countDigitsInANumericString('123456')); // 6

Sign up to request clarification or add additional context in comments.

3 Comments

It worked but I needed it without any string I should've made that clearer, thank you though
@gorak as of ES2015 it's probably better to use Number.isNaN to avoid some edge cases with the global isNaN function. But yes... that's a good alternative.
For anyone curious, the difference between Number.isNaN and Number.isFinite is that Number.isNaN(Number.Infitiy) returns false. In this case, it's hard to see how you end up with an infinite value so both would work.
1

I updated your above function to count the 0s at the beginning of your number string. Though there can be other ways too.

var y = '000102';
var num = parseInt(y);
var count = 0;

while (y[count] == '0') {
  ++count;
}
if (num >= 1) {
  ++count;
}

while (num / 10 >= 1) {
  num /= 10;
  ++count;
}

console.log(count);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.