开发者

String format in .NET: convert integer to fixed width string?

I have an int in .NET/C# that I want to convert to a specifically formatted string.

If the value is 1, I want the string to be "001".

10 = "010".

116 = "116".

etc.开发者_如何学JAVA..

I'm looking around at string formatting, but so far no success. I also won't have values over 999.


The simplest way to do this is use .NET's built-in functionality for this:

var r = 10;
var p = r.ToString("000");

No need for looping or padding.


Take a look at PadLeft.

ex:

int i = 40;

string s = i.ToString().PadLeft(3, '0'); 

s == "040"


Another option would be:

i.ToString("d3")


I recall seeing code like this to pad numbers with zeros...

int[] nums = new int[] { 1, 10, 116 };

foreach (int i in nums)
{
    Console.WriteLine("{0:000}", i);
}

Output:

001
010
116


For the sake of completeness, this way is also possible and I prefere it because it is clearer and more flexible.

int value = 10;

// 010 
resultString = $"{value:000}";

// The result is: 010 
resultString = $"The result is: {value:000}";


If we want to use it in a function with variable fixed length output, then this approach

public string ToString(int i, int Digits)
{
 return i.ToString(string.Format("D{0}", Digits));
}

runs 20% faster than this

return i.ToString().PadLeft(Digits, '0'); 

but if we want also to use the function with a string input (e.g. HEX number) we can use this approach:

public string ToString(string value, int Digits)
 {
 int InsDigits= Digits - value.Length;
 return ((InsDigits> 0) ? new String('0', InsDigits) + value : value);
 }


Every time I have needed to append things to the beginning of a string to match criteria like this I have used a while loop. Like so:

while (myString.length < 5) myString = "0" + myString;

Although there may be a string.format way to do this as well this has worked fine for me before.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜