- Home /

# How to convert and integer into an Array of his digits

Hi guys,

I'm working on a simple game and I have an interger made of X digits let's say 0123456789. now what I would like to do is to obtain an array that has X spaces in which each one contain only one of the digits of the integer. If it easier It will be fine even with a string since than I can convert string into integer.

Thank you.

**Answer** by mattyman174
·
May 15, 2014 at 12:11 PM

Try this on for size.

```
public static int[] IntToIntArray(int num)
{
if (num == 0)
return new int[1] { 0 };
List<int> digits = new List<int>();
for (; num != 0; num /= 10)
digits.Add(num % 10);
int[] array = digits.ToArray();
System.Array.Reverse(array);
return array;
}
```

Modulo is so wonderful :)

Essentially all your doing here is dividing the original given integer by 10 each time thereby forcing each individual number from the end to beginning into a decimal and using modulo we can just get that number each time.

Then simply reverse the array created and you have the number as an int array.

Just to note some constraints on this solution though, you cant give it negative integers and be careful you dont start trying to feed it something bigger than an integer, like a long.

One small detail is that C#'s modulo operator returns a negative number for negative values. If you want the digits without sign, you should first `Mathf.Abs()`

the value before adding it to `digits`

.

**Answer** by Naveen Kumar
·
May 15, 2014 at 11:55 AM

U can Write Like

lets say no = 123456789; int rem = 0; vector arr;

While( no ) {

rem = no%10;

arr.pushback( rem );

no = no/10;

}

And U can have all the digits in reverse order

**Answer** by shadabeqbal
·
Mar 20, 2018 at 07:34 AM

static int[] Int_to_array(int n)

{

int j = 0;

int len = Integer.toString(n).length();

int[] arr = new int[len];

while(n!=0)

{

arr[len-j-1]=n%10;

n=n/10;

j++;

}

return arr;

}

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.

### Follow this Question

### Related Questions

A node in a childnode? 1 Answer

Inventory system using an array... 3 Answers

Array Of Bools 4 Answers

How can I stretch an array of points, interpolating the values. 1 Answer

transform.rotation problem 1 Answer