2017-06-04 115 views
0

好吧,我有一个ListBox显示产品(他们是一个自定义的类,并有ID,名称,价格),在绑定列表中..我希望ListBox显示项目名称和价格。列表框(lbProductsChosen)将“DataTextField”设置为名称并将DataValueField设置为该ID。我正在使用PreRender事件来检查每个项目,从绑定列表(blProducts)中查看它的价格等等,它的工作效果很好。我用这个名字和价格显示在列表中。但是,当它显示时,尽管我使用String.Format格式化,结果仍然是一个十进制数(例如3.20000),它看起来很丑。有谁知道为什么它的工作显示它,但没有显示它,我想如何格式化。ASP.net ListBox货币格式化

protected void lbProductsChosen_PreRender(object sender, EventArgs e) 
    { 
     foreach (ListItem item in lbProductsChosen.Items) 
     { 
      string currentDescription = item.Text; 
      int convertedValue = Convert.ToInt32(item.Value); 
      for (int i = 0; i < blProducts.Count; i++) 
      { 
       if (blProducts[i].ProductID == convertedValue) 
       { 
        decimal ItemPrice = blProducts[i].Price; 
        string convertedPrice = ItemPrice.ToString(); 
        string currentPrice = String.Format("{0:c}", convertedPrice); 
        string currentDescriptionPadded = currentDescription.PadRight(30); 
        item.Text = currentDescriptionPadded + currentPrice; 
       } 
      } 
     } 
    } 

回答

0

MSDN状态下面对String.Format方法。

通常,通过使用由CultureInfo.CurrentCulture属性返回的当前区域性的约定,将参数列表中的对象转换为它们的字符串表示形式。

如果您使用货币格式说明符c它将使用在系统设置中定义的货币格式。看看control panel - >region - >additional settings - >currency。也许你已经搞乱了设置。

enter image description here


如果你想忽略本地设置这将使意义的货币,你可以做到以下几点。 (例如,在美元与百达小数点后两位)

decimal price = 12.10999999m; 
String.Format("${0:0.00}", price); 

$ 12.10条

注意String.Format不正确四舍五入的数量只是砍下。

+0

谢谢。本地设置是正确的,因为我在我的程序的其他部分使用货币转换,它的工作原理。只是不知道为什么它不在这里格式化,没有错误。我会用你的例子尝试一下,希望它可以工作,尽管它可能不会像我使用的格式那样注册它,因为它实际上不是从本地设置。明天会提供反馈。 – Sick