Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.Format "C" (currency) is returning the string "C" instead of formatted text

Tags:

c#

format

I am trying to ensure that the text in my control derived from TextBox is always formatted as currency.

I have overridden the Text property like this.

   public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {                
            double tempDollarAmount = 0;
            string tempVal = value.Replace("$", "").Replace(",","");
            if (double.TryParse(tempVal, out tempDollarAmount))
            {
                base.Text = string.Format("C", tempDollarAmount);
            }
            else
            {                 
                base.Text = "$0.00";
            }                
        }
    }

Results:

  • If I pass the value "Text" (AmountControl.Text = "Text";) , the text of the control on my test page is set to "$0.00", as expected.
  • If I pass the value 7 (AmountControl.Text = "7";) , I expect to see "$7.00", but the text of the control on my test page is set to "C".

I assume that I am missing something very simple here. Is it something about the property? Or am I using the string format method incorrectly?

like image 576
NetHawk Avatar asked Nov 30 '22 12:11

NetHawk


2 Answers

Instead of "C" put "{0:c}"

For more string formatting problems go here

like image 187
Jason Punyon Avatar answered Dec 04 '22 12:12

Jason Punyon


You can also use tempDollarAmount.ToString("C").

like image 30
Joe Avatar answered Dec 04 '22 11:12

Joe