How can I "break up" numbers into smaller pieces in javascript? - Stack Overflow

I think the title needs some explaining. I wan't to make my program break up a number into smaller

I think the title needs some explaining. I wan't to make my program break up a number into smaller bits.

For example, it would break 756 into 700, 50 and 6. 9123 would be 9000, 100, 20 and 3. Is there any way I can do this for any reasonably sized number?

I think the title needs some explaining. I wan't to make my program break up a number into smaller bits.

For example, it would break 756 into 700, 50 and 6. 9123 would be 9000, 100, 20 and 3. Is there any way I can do this for any reasonably sized number?

Share Improve this question asked May 15, 2016 at 2:39 EdwinEdwin 4001 gold badge5 silver badges19 bronze badges 6
  • How do you want the output formatted? Into an array of numbers? – jmancherje Commented May 15, 2016 at 2:42
  • You can use a bination of dividing and modulus to get your desired outputs. For example, 756 / 100 = 7, and 7 * 100 = 700. Then 756 % 100 = 56. 56 / 10 = 5, and 5 * 10 = 50. etc... – BradStell Commented May 15, 2016 at 2:48
  • @jmancherje Yes, an array of numbers – Edwin Commented May 15, 2016 at 2:52
  • Brad, what if all the numbers are randomly generated? Is there a way the puter can tell by itself what to do? – Edwin Commented May 15, 2016 at 2:54
  • 1 Well, thats part of the fun on your part. You need to figure out how large the number is, so you know what number to start dividing by. One solution is to divide by increasing values of 10 until the answer is less than 0. There are more optimal ways I'm sure. So divide by 10, then 100, then 1000, etc until the answer is less than 0. – BradStell Commented May 15, 2016 at 2:55
 |  Show 1 more ment

3 Answers 3

Reset to default 7

Working Example

Here is a function that can do it:

function breakNumbers(num){
  var nums = num.toString().split('');
  var len = nums.length;
  var answer = nums.map(function(n, i) {
    return n + (Array(len - i - 1).fill(0)).join('');
  });
    return answer.map(Number).filter(function(n) {return n !== 0;});
}
function breakup(number) {
  var digits = String(number).split('')
  return digits.map(function(digit, i) {
    return Number(digit.concat("0".repeat(digits.length - i - 1)))
  }).filter(function(n) { return n !== 0 })
}

So first, we want to cast the number to a string, so we pass it into the String primitive like so: String(number)

Thus, calling the split method on the array and passing in an empty string (which tells it to split for every character) results in an array of the digits, i.e. ["7", "5", "6"]

We can leave them as strings for now because it makes the next part a little easier. Using the map function, you can pass a function which should be called on each element in the array. Besides the first argument to this function, there's an optional second argument which is the index of the item in the array. This will turn useful in our case, since where a number is in the array indicates what place it is.

Check it out, the value returned by the function passed to map takes the current number string and concats another string onto it, which is a number of repeated "0"s. That number is determined by looking at the parent array's length and subtracting it from the index of the current item being looped on, minus one. This is because arrays are 0-indexed in JavaScript--if we just subtracted digits.length from the i (index) for the first iteration, the values would be 3 and 0 respectively, so you'd end up with 7000 for the first value if you passed in 756. Note also that in our return statement inside the map function, we wrap it back in a Number primitive to cast it back from a string.

Also, you didn't mention this, but I assume you'd rather not have numbers which equal 0 in your example. By calling filter on the final array before its returned, we can effectively make sure that only items which are not equal to 0 are returned. Thus, if you call breakup(756) you'll recieve [700, 50, 6], but breakup(706) will give you [700, 6] instead.

Instead of using split() to break out digits, I used a regex to tokenize the number string. This way, we can easily handle any trailing decimals by treating a digit followed by a decimal point and any further digits as a single token. This also makes it possible to handle digits as part of a larger string.

function splitNumber( number ) {
    var parts = [];
    var re = /(\d(?:\.\d*)?)/g;
    while(next_part = re.exec(number)) {
        // adjust place value
        parts.forEach( function(element, index) {
            parts[index] = 10 * element;
        } );

        parts.push( next_part[0] );
    }
    return parts.map(Number).filter(function(n) {return n !== 0});
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744276070a4566337.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信