Introduction
In this tip, I will show one method of returning all the digits of an integer in an array.
Using the Code
public static class Extensions
{
static int[] Digits(this int value)
{
int sign = Math.Sign(value);
value *= sign;
int count = (int)Math.Truncate(Math.Log10(value)) + 1;
int[] list = new int[count];
for (int i = count - 1; i >= 0; --i)
{
int nextValue = value / 10;
list[i] = value - nextValue * 10;
value = nextValue;
}
list[0] *= sign;
return list;
}
}
Points of Interest
Note that the first array position preserves the sign of the number.
History
- 9 March 2017: First version