【问题标题】:ASP.net ListBox currency formattingASP.net ListBox 货币格式
【发布时间】:2017-06-04 18:59:20
【问题描述】:

好的,伙计们,我有一个列表框,它显示绑定列表中的产品(它们是自定义类,并具有 ID、名称、价格)。我希望列表框显示项目名称和价格。列表框 (lbProductsChosen) 将“DataTextField”设置为 Name 并将 DataValueField 设置为 ID。我正在使用 PreRender 事件来检查每个项目,从绑定列表(blProducts)等中查看它的价格,它工作得很好。我得到了列表中显示的名称和价格。但是,当它显示时,尽管我使用 String.Format 对其进行了格式化,但结果仍然是一个十进制数(例如 3.20000),而且看起来很难看。有谁知道为什么它可以显示它,但没有显示它我希望它的格式。

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

【问题讨论】:

    标签: c# asp.net listbox


    【解决方案1】:

    MSDN 陈述了以下关于String.Format 方法的内容。

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

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


    如果您想忽略对货币有意义的本地设置,您可以执行以下操作。 (以美元计,小数点后两位)

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

    12.10 美元

    请注意,String.Format 没有正确舍入数字,而是将其截断。

    【讨论】:

    • 谢谢。本地设置没问题,因为我在程序的其他部分使用货币转换并且它有效。只是无法弄清楚为什么它不在这里格式化,没有错误。我将使用您的示例进行尝试,并希望它可以工作,尽管它可能不会像我使用的格式那样注册它,因为它实际上不是来自本地设置。明天会给出反馈。
    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多