Search code examples
javascriptarraysfunctionmathrounding

How do I use Javascript to figure out the quantity of 1000s, 100s, 10s, 1s in a number?


Here's an example of what I'm trying to do...

Let's say I have the number 73,284.

The number of thousands is 73 (73,284 divided by 1,000).

The number of hundreds is 2 (284 divided by 100).

The number of tens is 8 (84 divided by 10).

The number of singles is 4 (4 is left).

What I need is a Javascript function that would take the number 73,284 and create 4 numbers from it using the criteria above.

So if the number was 73,284, I'd pass that number into the function as a parameter and the function would return an array that looks like this, [73,2,8,4].

I tried to use the Math.round() function. It seemed to work for the thousands, but not necessarily for the hundreds, tens, and singles.


Solution

  • You can do this by keeping track of how many thousands, hundreds and tens you have and removing these as you go. A little simple arithmetic.

    function get(num){
          const thousands = Math.floor(num/1000)
          const hundreds = Math.floor((num-thousands*1000)/100);
          const tens = Math.floor((num-thousands*1000-hundreds*100)/10);
          const units = Math.floor(num-thousands*1000-hundreds*100-tens*10)
          return [
            thousands,
            hundreds,
            tens,
            units
          ]
    }
    
    const [th,hu,te,un] = get(73284)
    
    console.log("Thousands=",th);
    console.log("Hundreds=",hu);
    console.log("Tens=",te);
    console.log("Units=",un);