How to Format a String as a Number With Padding in Asp.Net

Description:-

Here we will see how to Format string as a number with padding different Character, Number and Sign etc.

Step 1: Drag Labels in your Browser.

<div>
   <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
   <br />
   <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
   <br />
   <asp:Label ID="Label3" runat="server" Text=""></asp:Label>
   <br />
   <asp:Label ID="Label4" runat="server" Text=""></asp:Label>
   <br />
   <asp:Label ID="Label5" runat="server" Text=""></asp:Label>
   <br />
   <asp:Label ID="Label6" runat="server" Text=""></asp:Label>
   <br />
   <asp:Label ID="Label7" runat="server" Text=""></asp:Label>
</div>

Step 2: Now go to Code behind and code for how to set padding in String. Here I have set different Example with padding in String.

protected void Page_Load(object sender, EventArgs e)
{
    //this line create an int variable.
    int number = 123;

    Label1.Text = "formatted string";

    int length = number.ToString().Length + 1;
    string dValue = "D" + length.ToString();

    int length2 = length + 5;

    Label1.Text += "Number: " + number;
    //format string using ToString method
    Label2.Text += "number padding with zero: " + number.ToString("D4");
    //format string using string.format method.
    Label3.Text += "number padding with zero: " + string.Format("{0:D4}", number);

    //dynamically determine number length and format string.
    Label4.Text += "number dynamic padding with zero: " + number.ToString(dValue);

    //another technique to format string using padleft method.
    Label5.Text += "number padding with zero length 10: " + number.ToString().PadLeft(length2, '0');
    Label6.Text += "number padding with plus sign:"+ number.ToString().PadLeft(length2, '+');
    Label7.Text += "number padding with ‘A’ character: " + number.ToString().PadLeft(length2, 'A');
}

Check in your browser and see output.

Related Posts

Previous
Next Post »

Thanks for comments.....