4

I want the user to enter a number and print back the amount of digits of that number.

I know that I can use length, but my homework asking for while loop.

This is what I have so far:

var num;
var count = 0;

num = prompt('Enter number: ');

function counter(x, y) {
  while (x > 0) {
    y++;
    x /= 10;
  }
  return y;
}

var result = counter(num, count);

console.log(result);

When I give the number 3456 (example), I get back the number 328. I want it to print back the number 4.

9
  • 3
    convert the number to string and access the .length property Commented Nov 11, 2019 at 12:38
  • @nickzoum well that's one way to do it Commented Nov 11, 2019 at 12:39
  • 2
    Should 0 return 0 or 1? Commented Nov 11, 2019 at 12:42
  • 1
    @EricWu When you learn a musical instrument, you are told to play scales and arpeggios, not because they are pleasant to hear, but because they teach you technique. Coding exercises are often similar: simplified and constrained, so that you learn ways to think about algorithms and program design. Often, there can be a whole sequence of "now do it without this built-in". Commented Nov 11, 2019 at 12:48
  • 1
    Let's also mention the mathematical way to do this without a loop and without treating it as a string. That's taking the integral part of the 10-based logarithm and adding 1. Math.floor(Math.log10(Math.abs(num))) + 1 Taking the absolute value makes it also work with negative numbers. 0 is a special case. Commented Nov 11, 2019 at 12:57

6 Answers 6

3

This line:

x /= 10;

Should be changed to:

x = Math.floor(x / 10);

The logic assumes integer division: 1234 is supposed to become 123, 12, 1 and 0. JavaScript does not have built in integer division so you need to use Math.floor to emulate it. Complete example with some fixes:

function countDigits(num) {
  var count = 0;
  while (num > 0) {
    num = Math.floor(num / 10);
    count++;
  }
  return count;
}

var num;
do {
  num = Number(prompt("Enter number:"));
} while (Number.isNaN(num));
num = Math.abs(num); // just in case you want to handle -ve numbers
var result = countDigits(num);
console.log(result);

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

Comments

1

The problem is that the division operation will eventually end up converting x to a float and you'll have something like:

x / 10 === 0.1;
x / 10 === 0.01;
x / 10 === 0.001;
....

if you always parse (round) the result of the division to an integer, you'll get the expected result.

var num;
var count = 0;

num = prompt('Enter number: ');

function counter(x, y) {
  while (x > 0) {
    y++;
    x = parseInt(x / 10);
  }
  return y;
}

var result = counter(num, count);

console.log(result);

1 Comment

Using parseInt on numbers is wrong... "parse" means parse something out of strings.
1

You could check againt a number by taking the power of a decimal count.

function counter(value) {
    var decimals = 0;
    do {
        decimals++;
    } while (value >= 10 ** decimals)
    return decimals;
}

console.log(counter(0));
console.log(counter(1));
console.log(counter(7));
console.log(counter(42));
console.log(counter(999));
console.log(counter(1000));
console.log(counter(1001));

Comments

1

First of all you should convert the input into a number, preferably using the Number function (using unary + has the same effect).

Secondly a division like 5 / 10 will return 0.5 which is bigger than 0. You should instead check if the number is bigger than or equal to 1.

function counter(num) {
  num = Math.abs(num) / 10;
  var count = 1;  
  while (num >= 1) {
    count++;
    num /= 10;
  }
  return count;
}

console.log(counter(+prompt('Enter number: ')));

You could also use a do while loop and avoid having an extra division outside the loop.

Comments

1

As others have pointed out, y doesn't need to be a parameter, it can be a local variable. But that's not your problem; let's add some extra logging to your loop:

function counter(x) {
  let y=0;
  while (x > 0) {
    console.log("x=" + x + ", y=" + y);
    y++;
    x /= 10;
  }
  return y;
}
counter(3456);

The output looks like this:

x=3456, y=0
x=345.6, y=1
x=34.56, y=2
x=3.4560000000000004, y=3
x=0.3456, y=4
x=0.03456, y=5
...

You wanted the loop to stop at 0.3456, but that's still more than 0. (This mistake actually gives you a chance to learn something extra: can you explain why the loop ever finishes at all?)

Hopefully this will give you enough of a hint to complete the homework assignment - remember that debugging is an extremely important part of programming.

Comments

0

Please don't use cycles to measure length of an integer...

Use math instead! Logarithm will do much better job for you.

function numberLength(number) {
    return Math.floor(Math.log10(Math.abs(number))) + 1
}

console.log(numberLength(YOUR_NUMBER));

This code returns NaN when the input is 0. I think it depends on your philosophy what length the 0 should have, so I am leaving that case unhandled.

5 Comments

It is a homework assignment related to JavaScript and specifically asks to use a loop, not Math.
@Salman A I know, but there will be other people reading this when doing different homework, and search engine might lead them to this question. So they should be able to find a better solution here. :-)
it's better to use Math.floor rather than parseInt for numeric arguments
@georg Thanks! I actually don't know anything about JavaScript, haha :D
This is a coding exercise. If you think the question should make that clearer, then propose an edit to the question, but since it already says "I know that I can use length, but my homework asking for while loop" this is simply an incorrect answer to the question as asked.

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.