问题
Instead of doing this, I want to make use of string.format() to accomplish the same result:
if (myString.Length < 3)
{
myString = "00" + 3;
}
回答1:
If you're just formatting a number, you can just provide the proper custom numeric format to make it a 3 digit string directly:
myString = 3.ToString("000");
Or, alternatively, use the standard D format string:
myString = 3.ToString("D3");
回答2:
string.Format("{0:000}", myString);
回答3:
It's called Padding:
myString.PadLeft(3, '0')
回答4:
(Can't comment yet with enough reputation , let me add a sidenote)
Just in case your output need to be fixed length of 3-digit , i.e. for number run up to 1000 or more (reserved fixed length), don't forget to add mod 1000 on it .
yourNumber=1001;
yourString= yourNumber.ToString("D3"); // "1001"
yourString= (yourNumber%1000).ToString("D3"); // "001" truncated to 3-digit as expected
Trail sample on Fiddler https://dotnetfiddle.net/qLrePt
回答5:
This is how it's done using string interpolation C# 7
$"{myString:000}"
回答6:
"How to: Pad a Number with Leading Zeros" http://msdn.microsoft.com/en-us/library/dd260048.aspx
回答7:
You can also do : string.Format("{0:D3}, 3);
回答8:
Does it have to be String.Format?
This looks like a job for String.Padleft
myString=myString.PadLeft(3, '0');
Or, if you are converting direct from an int:
myInt.toString("D3");
回答9:
This is a short hand string format Interpolation:
$"{value:D3}"
来源:https://stackoverflow.com/questions/12570807/format-string-to-a-3-digit-number