An Extension to Get All the Digits of a Number






3.47/5 (10 votes)
Gets the digits and the sign of an integer in an array
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)
{
// get the sign of the value
int sign = Math.Sign(value);
// make the value positive
value *= sign;
// get the number of digits in the value
int count = (int)Math.Truncate(Math.Log10(value)) + 1;
// reserve enough capacity for the digits
int[] list = new int[count];
for (int i = count - 1; i >= 0; --i)
{
// truncate to get the next value
int nextValue = value / 10;
// fill the list in reverse with the current digit on the end
list[i] = value - nextValue * 10;
value = nextValue;
}
// make the first digit the correct sign
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