C# convert int to string with padding zeros?

前端 未结 13 1772

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 06:59
    public static string ToLeadZeros(this int strNum, int num)
    {
        var str = strNum.ToString();
        return str.PadLeft(str.Length + num, '0');
    }
    
    // var i = 1;
    // string num = i.ToLeadZeros(5);
    
    0 讨论(0)
  • 2020-11-22 07:08

    Easy peasy

    int i = 1;
    i.ToString("0###")
    
    0 讨论(0)
  • 2020-11-22 07:09

    .NET has an easy function to do that in the String class. Just use:

    .ToString().PadLeft(4, '0')  // that will fill your number with 0 on the left, up to 4 length
    
    int i = 1; 
    i.toString().PadLeft(4,'0')  // will return "0001"  
    
    0 讨论(0)
  • 2020-11-22 07:11

    Here's a good example:

    int number = 1;
    //D4 = pad with 0000
    string outputValue = String.Format("{0:D4}", number);
    Console.WriteLine(outputValue);//Prints 0001
    //OR
    outputValue = number.ToString().PadLeft(4, '0');
    Console.WriteLine(outputValue);//Prints 0001 as well
    
    0 讨论(0)
  • 2020-11-22 07:13

    Here I want to pad my number with 4 digit. For instance, if it is 1 then it should show as 0001, if it 11 it should show as 0011.

    Below is the code that accomplishes this:

    reciptno=1; // Pass only integer.
    
    string formatted = string.Format("{0:0000}", reciptno);
    
    TxtRecNo.Text = formatted; // Output=0001
    

    I implemented this code to generate money receipt number for a PDF file.

    0 讨论(0)
  • 2020-11-22 07:14

    i.ToString().PadLeft(4, '0') - okay, but doesn't work for negative numbers
    i.ToString("0000"); - explicit form
    i.ToString("D4"); - short form format specifier
    $"{i:0000}"; - string interpolation (C# 6.0+)

    0 讨论(0)
提交回复
热议问题