I need to split a number into groups of digits and then place those digits into an array. I'll then be doing some simple math with those numbers and then inserting them into a textbox.
So far, I have only found how to split a number into individual digits as shown below:
var number = 12354987,
output = [],
sNumber = number.toString();
for (var i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));
}
console.log(output);
A fairly concise way of doing this would be to use a regular expression. For example, to split the number up into groups of up to 3 digits, you could use the following:
This returns the following array:
To split into N digits, you can use the
RegExp
constructor instead:Then
result
would be:A simple way to change the values of
result
back into numbers would be to usemap
, withNumber
(which performs a type conversion in a non-constructor context):Then
numbers
would be:While there may be a simpler way to do this using Regexp, you could try this:
Now that you have
output
with individual digits, you can use another array to split it into pieces ofn
size, like so:This outputs an array of arrays of size
n
.If
n
= 2 it outputs the array (stored infinal
):See working example on JSFiddle.net.
You can use regular expression to obtain the result you want.
If you want to group starting by left, the regular expression is quite simple:
If, instead, you want to start by right side, e.g. like a currency format, the regular expression needs to be more articulate:
You can change the number of digit you want to group simply replacing
3
inside\d{3}
with the amount desired. You could also obtain such value from a variable, in that case you have to use the RegExp constructor to build your regexp instance.Edit: To convert the
output
to numbers again you can use the array's map method as follow:Hope it helps.