简体   繁体   中英

need a better way add leading digits to int and return array of digits

I need to create a modulus check which adds leading digits, lets say 0, to a seed int. I then need to return an array of digits in the array as I need to do a calculation on each digit to return a new whole number.

my code is as follows,

var seed = 1234;
var seedString = seed.ToString();
var test = new List<int>();

for(int i = 0; i < 10 - seedString.Length; i++)
{
    test.Add(0);
}

var value = seed;
for(int i = 0; i < seedString.Length; i ++)
{

    test.Insert(10 - seedString.Length, value % 10);
    value = value / 10;

}

is there an easier way of doing this?

If you want to convert your number to a 10-digit string, you can format the number using a Custom Numeric Format String as follows:

string result = seed.ToString("0000000000");
// result == "0000001234"

See: The "0" Custom Specifier


If you need a 10-element array consisting of the individual digits, try this:

int[] result = new int[10];
for (int value = seed, i = result.Length; value != 0; value /= 10)
{
    result[--i] = value % 10;
}
// result == new int[] { 0, 0, 0, 0, 0, 0, 1, 2, 3, 4 }

See also: Fastest way to separate the digits of an int into an array in .NET?

Try this:

int myNumber = 1234;  
string myStringNumber = myNumber.ToString().PadLeft(10, '0');

HTH

Another shorthand way of getting the string representation would be

int num = 1234;
num.ToString("D10");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM