c# - How to format a string with leading zeros

Format a String with leading zeros
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can format a String object with leading zeros. In this .net c# tutorial code we will add a specified number of zeros at the beginning of a String instance. The String PadLeft() method allows us to achieve this.

The String PadLeft() method returns a new String of a specified length in which the beginning of the current String is padded with spaces or with a specified Unicode character.

The String PadLeft(int totalWidth, char paddingChar) method overload returns a new String that right-aligns the characters in this instance by padding them on the left with a specified Unicode character for a specified total length.

So we can pass zero ‘0’ for the paddingChar parameter to this method and for totalWidth, we can add the specified number with the String instance length. By doing this, the method returns a String with leading specified numbers of zeros.

The String PadLeft(Int32, Char) overload returns a new String that is equivalent to this instance but right-aligned and padded on the left with as many paddingChar characters as needed to create a length of totalWidth. This method throws ArgumentOutOfRangeException if totalWidth is less than zero.

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
        //this line create a string variable.
        string stringValue = "asp.net examples";

        //this line create an integer variable.
        int intValue = 12345;

        Label1.Text = "string value: " + stringValue.ToString();
        Label1.Text += "<br />integer value: " + intValue.ToString();

        //string format left padding and right padding
        Label1.Text += "<br /><br />string format left padding with 0: " + stringValue.ToString().PadLeft(stringValue.Length + 1, '0');
        Label1.Text += "<br />string format left padding with 3 zeros: " + stringValue.ToString().PadLeft(stringValue.Length + 3, '0');

        Label1.Text += "<br /><br />string format number to leading 2 zeros: " + intValue.ToString().PadLeft(intValue.ToString().Length + 2, '0');
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string format leading zeros</title>  
    <form id="form1" runat="server">  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string format leading zeros
        <hr width="550" align="left" color="Gainsboro" />  
        <br /><br />
            Text="string format leading zeros"  
More c# examples