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

末鹿安然 提交于 2019-12-23 06:47:32

问题


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...

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


回答1:


Take a look at PadLeft.

ex:

int i = 40;

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

s == "040"




回答2:


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.




回答3:


Another option would be:

i.ToString("d3")



回答4:


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



回答5:


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);
 }



回答6:


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.



来源:https://stackoverflow.com/questions/6399771/string-format-in-net-convert-integer-to-fixed-width-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!