Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number to tens, hundreds, thousands

I need a function that, given a number, say, 123, will output an array [100,20,3]. I've tried something like this (borrowed from another question on SO):

function separateNumberIntoUnits(n) {
    var arr = [];
    var i = 10;

    while (n > i / 10)
    {
        arr.unshift(n % i - n % (i / 10));
        i *= 10;
    }

    return arr;
}

and it works for all numbers except for 10, 100 etc. I've tried to figure out what's going on, but math isn't my strong side...

If there's a more efficient way to do this, feel free to write your own solution.

like image 425
daremkd Avatar asked Oct 27 '25 10:10

daremkd


2 Answers

I think this is the most efficient way:

function separateNumberIntoUnits(n) {
  if (n == 0) return [0];
  // n = Math.floor(n); // needed for decimal numbers
  var arr = [];
  var i = 1;

  while (n > 0) {
    arr.unshift((n % 10) * i);
    n = Math.floor(n / 10);
    i *= 10
  }

  return arr;
}

document.writeln(separateNumberIntoUnits(1234) + "<br />")
document.writeln(separateNumberIntoUnits(100) + "<br />")
document.writeln(separateNumberIntoUnits(10) + "<br />")
document.writeln(separateNumberIntoUnits(1) + "<br />")
document.writeln(separateNumberIntoUnits(0) + "<br />")

unshift is the best way to do it: Array.unshift vs Array.push and Array.reverse: https://jsperf.com/array-unshift-vs-array-push-and-array-reverse

like image 156
CoderPi Avatar answered Oct 29 '25 23:10

CoderPi


You could treat the number as a string.

Split it into an array of its digits, then map each digit to its decimal place by multiplying by the appropriate power of 10:

function separateNumberIntoUnits(n) {
  var s= n.toString().split('');
  
  return s.map(function(digit, n) {
    return digit * Math.pow(10, s.length - n - 1);
  });
}

document.body.innerHTML=
  separateNumberIntoUnits(1234) + '<br>' +
  separateNumberIntoUnits(100)  + '<br>' +
  separateNumberIntoUnits(0);
like image 22
Rick Hitchcock Avatar answered Oct 29 '25 23:10

Rick Hitchcock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!