Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

An Extension to Get All the Digits of a Number

0.00/5 (No votes)
10 Mar 2017 1  
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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here