4

我试图确保从 TextBox 派生的控件中的文本始终格式化为货币。

我已经像这样覆盖了 Text 属性。

   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";
            }                
        }
    }

结果:

  • 如果我传递值 "Text" (AmountControl.Text = "Text";) ,我的测试页面上的控件文本将按预期设置为 "$0.00"。
  • 如果我传递值 7 (AmountControl.Text = "7";) ,我希望看到 "$7.00",但我的测试页上的控件文本设置为 "C"。

我假设我在这里遗漏了一些非常简单的东西。是关于财产的吗?还是我错误地使用了字符串格式方法?

4

7 回答 7

13

而不是“C”放“{0:c}”

有关更多字符串格式问题,请转到此处

于 2009-01-27T16:22:06.003 回答
4

您也可以使用 tempDollarAmount.ToString("C")。

于 2009-01-27T16:22:38.843 回答
1

需要为“{0:C}”

于 2009-01-27T16:22:18.890 回答
1

它应该是“{0:C}”

于 2009-01-27T16:22:44.083 回答
1

是的,应该是:

base.Text = string.Format("{0:C}", tempDollarAmount);
于 2009-01-27T16:22:57.983 回答
1

它应该是:

base.Text = string.Format("{0:C}", tempDollarAmount);

并且请不要使用双精度表示货币,而是使用小数。

于 2009-01-27T16:24:22.597 回答
-1

它应该是:

Console.WriteLine("The value 99999 in various Format");
String s = "$";
String s1=s.Replace(s,"RS");
String s2 = String.Format("{0:c}", s1);
String s3="1000";
Console.WriteLine(s2 + s3);
于 2012-01-10T13:34:04.360 回答