简体   繁体   English

需要一种更好的方法将前导数字添加到 int 并返回数字数组

[英]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.我需要创建一个模数检查,它将前导数字(比如说 0)添加到种子 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:如果要将数字转换为 10 位字符串,可以使用自定义数字格式字符串格式化数字,如下所示:

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

See: The "0" Custom Specifier请参阅: “0”自定义说明符


If you need a 10-element array consisting of the individual digits, try this:如果您需要一个由单个数字组成的 10 元素数组,请尝试以下操作:

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?另请参阅: 将 int 的数字分隔到 .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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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