Format string to a 3 digit number

左心房为你撑大大i 提交于 2019-11-28 22:16:40

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");
Haitham Salem
 string.Format("{0:000}", myString);

It's called Padding:

myString.PadLeft(3, '0')

(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

This is how it's done using string interpolation C# 7

$"{myString:000}"

"How to: Pad a Number with Leading Zeros" http://msdn.microsoft.com/en-us/library/dd260048.aspx

You can also do : string.Format("{0:D3}, 3);

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

This is a short hand string format Interpolation:

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