C# convert int to string with padding zeros?

前端 未结 13 1774

In C# I have an integer value which need to be convereted to string but it needs to add zeros before:

For Example:

int i = 1;

When

相关标签:
13条回答
  • 2020-11-22 07:17
    i.ToString("0000");
    
    0 讨论(0)
  • 2020-11-22 07:19
    int p = 3; // fixed length padding
    int n = 55; // number to test
    
    string t = n.ToString("D" + p); // magic     
    
    Console.WriteLine("Hello, world! >> {0}", t);
    
    // outputs: 
    // Hello, world! >> 055
    
    0 讨论(0)
  • 2020-11-22 07:20

    Simply

    int i=123;
    string paddedI = i.ToString("D4");
    
    0 讨论(0)
  • 2020-11-22 07:20

    To pad int i to match the string length of int x, when both can be negative:

    i.ToString().PadLeft((int)Math.Log10(Math.Abs(x < 0 ? x * 10 : x)) + 1, '0')
    
    0 讨论(0)
  • 2020-11-22 07:21

    You can use:

    int x = 1;
    x.ToString("0000");
    
    0 讨论(0)
  • 2020-11-22 07:24

    C# 6.0 style string interpolation

    int i = 1;
    var str1 = $"{i:D4}";
    var str2 = $"{i:0000}";
    
    0 讨论(0)
提交回复
热议问题