Digits

A trick for taking apart numbers.

Division and remainder are related

Plain division

1234 / 10123.4

As you probably already know, dividing by 10 shifts the decimal place one position to the left.

Floor division

Math.floor(123.4)123

Math.floor does a regular division and throws away the decimal part.

Dividing by 10 with Math.floor throws away the ones place.

Remainder

1234 % 104

On the other hand, the remainder when we divide by 10 is just the digit in the ones place.

A new loop pattern

 while (n > 0) {
   const digit = n % 10
   // do something with digit
   n = Math.floor(n / 10);
 }

We could figure out how many digits a number has in it with some math but it’s easier to just loop, dividing by 10 at each step, until the number is 0.

Each time through the loop, the value of digit will be the value in the ones place before we do the division.

An example

const numNines = (n) => {
   let count = 0;
   while (n > 0) {
     if (n % 10 === 9) {
       count++
     }
     n = Math.floor(n / 10);
   }
   return count;
 }

numNines(1999)3