c# - How to format a string as a number with 2 decimal places

String format number 2 decimal places
string-format-number-2-decimal-places.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>
  
<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this section create int data type variables.
        int intVar = 12345;
        int intVar2 = 12;

        //this section create double data type variables.
        double doubleVar = 12345.5555;
        double doubleVar2 = 15.0;

        //this line create a decimal data type variable.
        decimal decimalVar = 12345.5555M;

        Label1.Text = "Formatted string..............";

        Label1.Text += "<br />Integer: " + intVar;
        Label1.Text += "<br />Integer2: " + intVar2;
        Label1.Text += "<br />Double: " + doubleVar;
        Label1.Text += "<br />Double2: " + doubleVar2;
        Label1.Text += "<br />Decimal: " + decimalVar;

        //format string using ToString method
        Label1.Text += "<br /><br /String format number 2 decimal places: " + intVar.ToString("0.00");
        Label1.Text += "<br />Another Integer: " + intVar2.ToString("0.00");
        Label1.Text += "<br />Another Integer: " + doubleVar2.ToString("0.00");

        //format string using string.format method.
        Label1.Text += "<br />String format integer variable: " + string.Format("{0:0.00}", intVar);
        Label1.Text += "<br />String format double variable: " + string.Format("{0:0.00}", doubleVar);
        Label1.Text += "<br />String format decimal variable: " + string.Format("{0:0.00}", decimalVar);
    }  
</script>  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string format number 2 decimal places</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string format number 2 decimal places
        </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 2 decimal places"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>
More c# examples