Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count digits of given number?

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.

like image 509
warzonemaster Avatar asked Mar 03 '23 04:03

warzonemaster


1 Answers

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);
like image 129
Salman A Avatar answered Mar 05 '23 17:03

Salman A