How to change 1 to 00001?

后端 未结 9 829
予麋鹿
予麋鹿 2021-01-03 23:59

I want to have numbers with a fixed digit count.

example: 00001, 00198, 48484

I can do like this:

    string value;
    if (number < 10)
          


        
相关标签:
9条回答
  • 2021-01-04 00:16

    According to the MS reference: http://msdn.microsoft.com/en-us/library/dd260048.aspx

    You can pad an integer with leading zeros by using the "D" standard numeric format string together with a precision specifier. You can pad both integer and floating-point numbers with leading zeros by using a custom numeric format string.

    So:

    To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

    Code:

    string value = number.ToString("D5");
    

    .NET fiddle: http://dotnetfiddle.net/0U9A6N

    0 讨论(0)
  • 2021-01-04 00:16
    string value = number.ToString("00000");
    
    0 讨论(0)
  • 2021-01-04 00:16

    You can do it this way :

    number.ToString("00000")
    
    0 讨论(0)
  • 2021-01-04 00:16

    Same as @Jojo's answer, but using C# 6's interpolated strings:

    var value = $"{number:00000}";
    
    0 讨论(0)
  • 2021-01-04 00:19

    Yes, there is:

    string value = String.Format("{0:D5}", number);
    
    0 讨论(0)
  • 2021-01-04 00:19

    Apart from String.Format, You can also use String.PadLeft

    value = number.ToString().PadLeft(5, '0');
    
    0 讨论(0)
提交回复
热议问题