Display number as percentage in Label using C# and VB.Net in ASP.Net

elvisidrizi1
 
on Aug 26, 2020 06:59 AM
1748 Views

Hello Everyone, 

I get values in percentage (%) but without the percentage sign in SQL and I use that number in Vb.net forms. 

The number has a lot of 0 digits so I use this code to reduce it :

LabelPercentage.Text = FormatNumber(LabelPercentage.Text, 2,)

What I need now is how to insert into the number the % sign?

I used this code to change the values from positive to negative and also to insert the percentage but it does not work. Here is the code :

If LabelPercentage.Text < 0 Then
    LabelPercentage.Text = (Convert.ToDecimal(LabelPercentage.Text.Trim().Replace("-", "+").Replace(" ", "%")))
    LabelPercentage.ForeColor = Color.DarkGreen
Else
    LabelPercentage.Text = (Convert.ToDecimal(LabelPercentage.Text.Trim().Replace(" ", "-").Replace(" ", "%")))
    LabelPercentage.ForeColor = Color.DarkRed
End If

Thank you  Best Regards, Elvis

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 26, 2020 07:12 AM
on Sep 02, 2020 02:19 AM

Hi elvisidrizi1,

Check this example. Now please take its reference and correct your code.

HTML

<asp:Label ID="LabelPercentage" runat="server" />

Code

C#

LabelPercentage.Text = string.Format("{0:0.00}", Convert.ToDecimal(LabelPercentage.Text));
if (Convert.ToDecimal(LabelPercentage.Text) < 0)
{
    LabelPercentage.Text = LabelPercentage.Text.Trim().Replace("-", "+").ToString() + "%";
    LabelPercentage.ForeColor = System.Drawing.Color.DarkGreen;
}
else
{
    LabelPercentage.Text = "-" + LabelPercentage.Text.Trim().Replace("+", "").ToString() + "%";
    LabelPercentage.ForeColor = System.Drawing.Color.DarkRed;
}

VB.Net

LabelPercentage.Text = FormatNumber(LabelPercentage.Text, 2,)
If LabelPercentage.Text < 0 Then
    LabelPercentage.Text = LabelPercentage.Text.Trim().Replace("-", "+").ToString() + "%"
    LabelPercentage.ForeColor = System.Drawing.Color.DarkGreen
Else
    LabelPercentage.Text = "-" + LabelPercentage.Text.Trim().Replace("+", "").ToString() + "%"
    LabelPercentage.ForeColor = System.Drawing.Color.DarkRed
End If