且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

String.Format 格式化货币的小问题

更新时间:2022-08-12 22:52:16

 今天在开发过程中,遇到一件让我觉得比较纳闷的事情:用String.Format 格式化充值金额的时候,我这样处理: String.Format("{0:C2}", dr["InpourMoney"].ToString())后,并没有像预期在充值金额前面加上货币符号¥,  反而 String.Format("{0:C2}", dr["InpourMoney"]) 这样处理后,在页面充值金额上面添加了¥符号。其中dr 是DataTable的Row。下面我们简单的例子来验证给大家看看:
代码Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
       lblText.Text = string.Format("{0:C2}", 12.345);            //¥12.35

       Object d = new Object();

       d = "12.345";

       lblText.Text = String.Format("{0:C2}", d);                  //12.345
       lblText.Text = String.Format("{0:C2}", d.ToString());       //12.345

       Object c = new Object();
       c = 12.345;
       lblText.Text = String.Format("{0:C2}", c);                 //¥12.35
       lblText.Text = String.Format("{0:C2}", c.ToString());      //12.345
    }
}

 

 似乎只有数字类型、或可以拆箱为数字类型的Object,String.Format才起效。