DEV Community

Jan Prazak
Jan Prazak

Posted on • Updated on

Get all separate digits of a number (TypeScript)

Do you need to "extract" each digit of a given number? Then this little TypeScript program is probably exactly what you're looking for. I have inserted some important comments about the "safe" input range, so make sure you are aware of it before using it in critical segments. There are many different solutions, this one avoids converting the number to a String internally, so it's a pure mathematical algorithm. (Note: I have updated the code to work correctly if given number is 0.)

/**
 * @param num A number in the int32 range [-2147483648 .. 2147483647]
 * @returns A number[] containing each digit of `num`.
 * If negative `num` given, resulting array will contain negatives numbers.
 */
function separateDigits(num: number): number[] {
  let arr: number[] = [];
  let lastDigit: number;

  num = toInt32(num);

  do {
    lastDigit = num % 10;
    arr.push(lastDigit);
    // Updating num to num/10 cuts off the last digit:
    num = toInt32(num / 10);
  }
  while (num !== 0);

  return arr.reverse();
}

/**
* Fast bitwise operation, truncates floating point number resulting in int32.
* The >> bitwise operator is used, an overflow occurs if number too large.
* A *safe* integer division in JavaScript would be Math.floor(x/y);
* @param f A (JavaScript) number between [-2147483648.999 .. 2147483647.999]
* @returns Input 'f' truncated to Int32.
*/
function toInt32(f: number): number {
  // Note that type "number" in JS is always "float" internally.
  return f >> 0;
}

console.log(separateDigits(3142520));

// Output:
// [3, 4, 1, 2, 5, 2, 0]
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
peerreynders profile image
peerreynders
    function toUint32(x: number) {
        return x >>> 0;
    }

    function toInt32(x: number) {
        return x >> 0;
    }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
amarok24 profile image
Jan Prazak

Thanks! I will update my code because right shift operators are more understandable to people coming from other languages. My solution using the ~~ operator seems to be very JS-specific :-/

Collapse
 
brense profile image
Rense Bakker • Edited

Wouldnt it be easier to convert the number to a string and just split it? Performance-wise it doesnt make much difference.

function separateDigits(num: number) : number[] {
  const numAsString = num + ''
  const strings = numAsString.split('')
  return strings.map(s => Number(s))
}

const numArr = separateDigits(1443643)
console.log(numArr)
Enter fullscreen mode Exit fullscreen mode

benchmark: jsben.ch/67w9k

Collapse
 
amarok24 profile image
Jan Prazak

Thanks for the jsbench link, seems to be a very usefuly online tool, I will save that.
And about the different solution with toString conversion, yes, why not, if you prefer type conversion and the map method. They are definitely many solutions to the same problem.