c# - How to format a string as a fixed length number

String format number fixed length
string-format-number-fixed-length.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;
        int length2 = length + 1;
        
        Label1.Text += "<br />Number: " + number;
        //format string using ToString method (fixed length 4 number)
        Label1.Text += "<br />4 digit fixed length number: " + number.ToString("0000");

        //format string using string.format method. (number fixed length 4 )
        Label1.Text += "<br />fixed length number: " + string.Format("{0:0000}", number);

        //another technique to format string using padleft method.
        Label1.Text += "<br />" + number.ToString().PadLeft(4, '0');
        Label1.Text += "<br />" + number.ToString().PadLeft(6, '0');
        Label1.Text += "<br />" + number.ToString().PadLeft(4, ' ');
        Label1.Text += "<br />" + number.ToString().PadLeft(4, '+');
        Label1.Text += "<br />" + number.ToString().PadLeft(4, '-');
        Label1.Text += "<br />" + number.ToString().PadLeft(4, '#');
        Label1.Text += "<br />" + number.ToString().PadLeft(4, '$');
    }  
</script>  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string format number fixed length</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string format number fixed length
        </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 fixed length"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>
More c# examples