从字符串中解析小数

Parsing Decimals from a String

我在 Web 表单上有一个下拉列表,其中包含项目名称和与之关联的价格(用户看不到)。我正在使用 selecteditem.Text 和 selectedvalue 来捕获项目名称和价格。为了打击所选值的重复条目,我存储了这样的条目

Signed Cap 10.0
Signed Glove 10.1
Signed Shirt 10.2
Bat Shavings .50
Hat Brim .50

然后使用下面的

解析出来
String[] str = dropdownlist1.SelectedValue.ToString().Split('.');
String itemprice = str[0].Trim();

我的语法很好用,除了十进制值!在蝙蝠刨花和帽檐上,我需要保留小数值!我应该改变什么或者我应该如何设置我的语法以允许重复的选定值或保留小数点?我知道使用 str[0] 是导致我丢失小数点的原因,但是 我该如何解决他们需要的 2 个(将来可能更多)场景保持原样?

您可以在 space 上拆分,并始终使用 linq 获取最后一个条目:

dropdownlist1.SelectedValue.ToString().Split(' ').Last();

请注意,您应该使用隐藏的 ItemId 作为选定值,而不是项目名称和价格,并使用 table 的查找:

ItemId|Name|Price
1|Hat|.50
2|Bat Shavings|.50
...

提交选择的id后,您可以更直接地查询名称和价格。此外,隐藏在表格中的价格不会阻止用户操纵价格。

很难从你的帖子中看出你是如何获取数据的,但我会将我的数据从数据库加载到数据对象中,然后将该对象绑定到下拉列表。

这里是InventoryClass我用来存储数据库中的数据:

public class Inventory
{
    public int ProductID { get; set; }
    public string ProductDescription { get; set; }
    public decimal ProductPrice { get; set; }

    public Inventory(int ID, string Description, decimal Price)
    {
        this.ProductID = ID;
        this.ProductDescription = Description;
        this.ProductPrice = Price;
    }

    public string DDLValue
    {
        get
        {
            return string.Format("{0}|{1}|{2}", ProductID, ProductDescription, ProductPrice);
        }
    }

    public string DDLText
    {
        get
        {
            return string.Format("{0} [{1}]", ProductDescription, ProductPrice.ToString("C"));
        }
    }
}

下面是如何配置页面控件的示例:

<asp:DropDownList ID="ddlProducts" runat="server" DataValueField="DDLValue" DataTextField="DDLText" />

在后面的页面代码中,将您的数据加载到下拉列表中:

protected void LoadProductsFromDatabase()
    {
        System.Collections.Generic.List<Inventory> My_DDL_Datasource = new System.Collections.Generic.List<Inventory>();

        // write your code to pull database values
        // populating list with sample data for Whosebug
        // make sure to use a replace statement to remove any delimiter characters that may be in the description
        My_DDL_Datasource.Add(new Inventory(1, "Product 1".Replace("|", ""), 0.50m));
        My_DDL_Datasource.Add(new Inventory(2, "Product 2".Replace("|", ""), 1.50m));
        My_DDL_Datasource.Add(new Inventory(3, "Product 3".Replace("|", ""), 0.50m));
        My_DDL_Datasource.Add(new Inventory(4, "Product 4".Replace("|", ""), 10.50m));

        ddlProducts.DataSource = My_DDL_Datasource;
        ddlProducts.DataBind();
    }

在后面的页面代码中,创建一个获取下拉列表选定值的方法:

protected Inventory GetSelectedProduct()
    {
        try
        {
            if (ddlProducts.Items.Count == 0)
            {
                // do nothing, fall thru will return null
            }
            else
            {
                string[] DDLValue = ddlProducts.SelectedValue.Split('|');

                int ivalue = 0;
                int.TryParse(DDLValue.GetValue(0).ToString(), out ivalue);

                decimal dvalue = 0.00m;
                decimal.TryParse(DDLValue.GetValue(2).ToString(), out dvalue);

                // only return object if the productid and product price were successfully parsed.
                // this logic assumes no products are free
                if (ivalue > 0 && dvalue > 0.00m)
                {
                    return new Inventory(ivalue, DDLValue.GetValue(1).ToString(), dvalue);
                }
            }
        }
        catch { }
        return null;
    }

在后面的页面代码中,用您选择的值做一些事情:

protected void DoSomethingWithValue()
    {
        Inventory MyInventoryItem = GetSelectedProduct();

        if (MyInventoryItem != null)
        {
            // selected item successfully parsed
            // do something with it.

            Response.Write(
                string.Format("Your selected product:<br />{0}<br />UniqueID: {1}<br />Price: {2}",
                Server.HtmlEncode(MyInventoryItem.ProductDescription),
                MyInventoryItem.ProductID,
                MyInventoryItem.ProductPrice.ToString("C")
            ));
        }
        else
        {
            // error parsing information stored in drop down list value
        }
    }

您需要 remove/replace 字符串中的所有字母字符并仅保留数字。

Regex rgx = new Regex("[^a-zA-Z]");
str = rgx.Replace(str, "").Trim();
decimal prc;
Decimal.TryParse(str, out prc);