C#将货币字符串转换为Double

Kri*_*own 2 c# string double casting currency

我对C#和.NET Framework有基本的了解,我已经获得了建立POS(销售点)屏幕的任务,我目前正在尝试将一个与货币相关的字符串转换为双倍的小砖墙.

我在屏幕上有两个列表框和几个产品按钮,按钮使用提供给我们的库类填充(基本上显示我们可以使用组件)

一个列表框保存产品名称,而另一个列表框保存该产品的价格,当选择产品按钮时,它从按钮文本中获取产品名称,并且在其标记内有价格被添加到价格列表框中.

我的问题是我想在列表框中显示价格作为货币也显示所有'0'我可以通过执行以下操作来做到这一点没问题

value.ToString("C");
string.Format("{0:C}",value);
Run Code Online (Sandbox Code Playgroud)

或使用转换等.

虽然因为我已经这样做了,如果我想通过双击从列表中删除一个项目我需要从总数中拿走价格,所以我需要转换回到双倍,尽管因为它的当前格式我得到一个错误试图执行我已经环顾四周的那个动作,我无论如何都无法找到它,我能看到的唯一选择就是保留字符串值,而不是将其转换为货币格式.

the ERROR: {"Input string was not in a correct format."}
Run Code Online (Sandbox Code Playgroud)

代码片段

 private void panelBtns_Click(object sender, EventArgs e)
    {
        Button panelBtn = (Button)sender;

        lstProduct.Items.Add(panelBtn.Text);

        double price = Convert.ToDouble(panelBtn.Tag);

        >>CURRENCY FORMAT>> lstPrice.Items.Add(string.Format("{0:C}",price));

        dblTotal = dblTotal + Convert.ToDouble(panelBtn.Tag);

        lblTotal.Text = string.Format("{0:C}", dblTotal);

        lblOutput.Text = "0";

        lblOutput.Tag = "0";
    }//End Panel Buttons 



 private void lstProduct_DoubleClick(object sender, EventArgs e)
    {
        int index = lstProduct.SelectedIndex;

        lstPrice.SelectedIndex = lstProduct.SelectedIndex ;

       >> ERROR HERE >> double price = Convert.ToDouble(lstPrice.GetItemText(lstPrice.SelectedItem));

        dblTotal = dblTotal - price; 

        lstProduct.Items.RemoveAt(index);

        lstPrice.Items.RemoveAt(index);

        lblTotal.Text = string.Format("{0:C}", dblTotal);

    }
Run Code Online (Sandbox Code Playgroud)

有没有人知道我怎么可能解决这个问题,我曾经创建了一个不可见的列表来存储标签的实际值,所以我可以在以后使用它,但是还有其他任何方法吗?

注意:我也知道使用双倍货币并不是非常可靠

Gab*_*abe 9

解析C格式的最简单方法可能是

Double.Parse(text, System.Globalization.NumberStyles.Currency)
Run Code Online (Sandbox Code Playgroud)

当然,您总是希望使用Decimal处理货币,并Decimal.Parse采用相同的参数.

但是,在这种情况下,您需要存储内部数值及其文本表示,而不是转换为字符串然后解析回数字.