【发布时间】:2014-01-03 22:01:15
【问题描述】:
我对 C# 和 .NET 框架有基本的了解,我被分配了构建 POS(销售点)屏幕的任务,我目前遇到了一个小砖墙,试图将与货币相关的字符串转换回双重的。
我在屏幕上有两个列表框和几个产品按钮,这些按钮是使用提供给我们的库类填充的(基本上表明我们可以使用组件)
One list box holds the product name while the other holds the price of that product, when a product button is selected it takes the product name from the buttons text and within its tag there is the price which is added to the list box价格。
我的问题是我想将列表框中的价格显示为一种货币,它也显示所有“0”我可以通过执行以下任一操作来做到这一点
value.ToString("C");
string.Format("{0:C}",value);
或使用转换等。
虽然因为我已经这样做了,如果我想通过双击从列表中删除一个项目,我需要从总数中去掉价格,所以我需要转换回双倍,尽管因为它的当前格式是我得到的尝试执行该操作时出现错误,我环顾四周,我似乎无法找到它,我能看到的唯一选择是将字符串值保持原样而不将其转换为货币格式。
the ERROR: {"Input string was not in a correct format."}
代码片段
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);
}
有人知道我该如何解决这个问题吗?我想创建一个不可见的列表来存储标签的实际值,以便以后可以使用它,但是还有其他方法吗?
注意:我也知道使用 double 作为货币不是很可靠
【问题讨论】:
-
你为什么用
double来代替decimal? -
通过解析UI元素的文本来读取数据真的是个坏主意。您应该将数据分开。阅读 MVVP 或 MVC 等模式。
-
@Gabe 在做 POS 屏幕的某些部分时,我们遵循了一些老师向我们展示的示例,我不想改变太多,以防我自己弄糊涂。
-
@DanAbramov 谢谢丹,我会记住这一点,看看你的建议。
-
这是一种非常糟糕的数据处理方式,也就是说,string.Format("{0:C}",price) 将美元符号“$”添加到字符串中,因此当您尝试将其转换回双倍,因为美元符号,它不再是数字,对。
标签: c# string casting double currency