JavaScript – Parsing A Number

 


If you should ever need to parse a number into an array of bits or a different base you can use the following function:

var splitNumber = (function(MAX) {
  for (; MAX + 1 - MAX == 1; MAX *= 2){}
  return function (num, radix) {
    // Validate num
    num = parseInt(num, 10);
    if (!isFinite(num) || 0 > num || num > MAX) {
      throw new Error('splitNumber() num argument must be a non-negative finite number less than ' + MAX);
    }
 
    // Validate radix
    radix = parseInt(radix || 10, 10);
    if (!(1 < radix && radix <= MAX)) {  // Also prevents NaN
      throw new Error('splitNumber() radix argument must be greater than 2 and less than ' + MAX);
    }
 
    return num.toString(radix).split('');
  };
})(1 << 30);

Here is an example of the tests and outputs:

I want to thank ildar for contributing the refinement of this function. 8-)

 

4 thoughts on “JavaScript – Parsing A Number”

Leave a Reply

Your email address will not be published. Required fields are marked *


9 + = seventeen

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">