c# - How to format a string as decimal

String format decimal
string-format-decimal.aspx

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

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //this section create decimal variables.
        Decimal decimalValue1 = 225.25M;
        Decimal decimalValue2 = 225.25555M;
        Decimal decimalValue3 = 225.25M;
        Decimal decimalValue4 = 225.2M;
        Decimal decimalValue5 = 225.0M;
        Decimal decimalValue6 = 22555555.0M;
        Decimal decimalValue7 = 225.0M;
        Label1.Text = "decimal value1: " + decimalValue1.ToString();
        Label1.Text += "<br />decimal value2: " + decimalValue2.ToString();
        Label1.Text += "<br />decimal value3: " + decimalValue3.ToString();
        Label1.Text += "<br />decimal value4: " + decimalValue4.ToString();
        Label1.Text += "<br />decimal value5: " + decimalValue5.ToString();
        Label1.Text += "<br />decimal value6: " + decimalValue6.ToString();
        Label1.Text += "<br />decimal value7: " + decimalValue7.ToString();

        //string format decimal using string.format method.
        Label1.Text += "<br /><br />format decimal value: " + string.Format("{0:0.##}", decimalValue1);
        Label1.Text += "<br />format decimal value: " + string.Format("{0:0.##}", decimalValue2);
        Label1.Text += "<br />format decimal value: " + string.Format("{0:0.##}", decimalValue3);
        Label1.Text += "<br />format decimal value: " + string.Format("{0:0.##}", decimalValue4);
        Label1.Text += "<br />format decimal value: " + string.Format("{0:0.##}", decimalValue5);
        Label1.Text += "<br />format decimal value(thousand separator): " + string.Format("{0:0,0.##}", decimalValue6);
        Label1.Text += "<br />format decimal value(with thousand separator): " + string.Format("{0:0,0.00}", decimalValue6);
        Label1.Text += "<br />format decimal value: " + string.Format("{0:0.##}", decimalValue7);
    }  
</script>  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string format decimal</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string format decimal
        </h2>  
        <hr width="550" align="left" color="Gainsboro" />  
        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="string format decimal"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>
More c# examples