Click here to Skip to main content
15,894,362 members
Articles / Programming Languages / C#
Tip/Trick

An Extension to Get All the Digits of a Number

Rate me:
Please Sign up or sign in to vote.
3.47/5 (10 votes)
10 Mar 2017CPOL 9.7K   5   4
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

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionSimpler solution Pin
codefabricator14-Mar-17 8:20
codefabricator14-Mar-17 8:20 
PraiseRe: Simpler solution Pin
TheGreatAndPowerfulOz14-Mar-17 8:57
TheGreatAndPowerfulOz14-Mar-17 8:57 
GeneralRe: Simpler solution Pin
Dennis_E15-Mar-17 4:53
professionalDennis_E15-Mar-17 4:53 
GeneralRe: Simpler solution Pin
TheGreatAndPowerfulOz15-Mar-17 5:44
TheGreatAndPowerfulOz15-Mar-17 5:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.