Format string to a 3 digit number

前端 未结 9 1316
说谎
说谎 2020-12-15 02:07

Instead of doing this, I want to make use of string.format() to accomplish the same result:

if (myString.Length < 3)
{
    myString =  \"00\"         


        
相关标签:
9条回答
  • 2020-12-15 02:44

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

    $"{myString:000}"
    
    0 讨论(0)
  • 2020-12-15 02:46

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

    0 讨论(0)
  • 2020-12-15 02:48

    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");
    
    0 讨论(0)
  • 2020-12-15 02:48

    (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

    0 讨论(0)
  • 2020-12-15 02:51

    This is a short hand string format Interpolation:

    $"{value:D3}"
    
    0 讨论(0)
  • 2020-12-15 02:55

    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");
    
    0 讨论(0)
提交回复
热议问题