c# - How to format a string as a number with padding

String format number padding
string-format-number-padding.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>
  
<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.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 += "<br />Number: " + number;
        //format string using ToString method
        Label1.Text += "<br />number padding with zero: " + number.ToString("D4");
        //format string using string.format method.
        Label1.Text += "<br />number padding with zero: " + string.Format("{0:D4}", number);

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

        //another technique to format string using padleft method.
        Label1.Text += "<br /><br />number padding with zero length 10: " + number.ToString().PadLeft(length2, '0');
        Label1.Text += "<br /><br />number padding with plus sign: " + number.ToString().PadLeft(length2, '+');
        Label1.Text += "<br /><br />number padding with 'A' character: " + number.ToString().PadLeft(length2, 'A');
    }  
</script>  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string format number padding</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string format number padding
        </h2>  
        <hr width="550" align="left" color="Gainsboro" />  
        <br />
        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="string format number padding"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>
More c# examples