简体   繁体   English

将字符串转换为Double从ListBox转换为TextBox

[英]Converting String to Double from ListBox to TextBox

// Calculating and diplaying pricing in list.
for (double MAX = 4.25; MAX >= MIN; MAX -= 0.05)
{
    Price = (X * MAX);
    prices = Price.ToString("c");
    listFinances.Items.Add(prices);
}

---

private void listFinances_SelectedIndexChanged(object sender, EventArgs e)
{
    string TotalPrice = listFinances.SelectedItem.ToString();
    double stateIncentive = (Convert.ToDouble(TotalPrice) / 4);
    txtStateTax.Text = stateIncentive.ToString();
}

So I'm trying to take a ListBox of string currency values, turn them into a double, divide them by 4, and display the result in a TextBox . 因此,我尝试获取一个包含字符串货币值的ListBox ,将它们转换为双ListBox货币,将它们除以4,然后在TextBox显示结果。 The user will select the ListBox value and the program should automatically divide by 4 and display. 用户将选择ListBox值,程序将自动除以4并显示。

It's not working however. 但是,它不起作用。 The program always does an exception throw when you click the ListBox item. 单击ListBox项时,程序始终会引发异常。 The exception is thrown at: 在以下位置抛出异常:

double stateIncentive = (Convert.ToDouble(TPrice) / 4);

saying that: 说:

It's not in the correct format. 格式不正确。

Can someone help me out here? 有人可以帮我吗?

You add your strings with the currency symbol. 您添加带有货币符号的字符串。 If you want to parse the string back to a double (but it is better use a decimal ) you need to tell the conversion that you have that symbol and ignore it 如果要将字符串解析为双精度型(但最好使用小数点 ),则需要告诉转换您具有该符号,然后忽略它

private void listFinances_SelectedIndexChanged(object sender, EventArgs e)
{
    string TotalPrice = listFinances.SelectedItem.ToString();
    decimal stateIncentive = decimal.Parse(TotalPrice, NumberStyles.Currency, CultureInfo.CurrentCulture) / 4);
    txtStateTax.Text = stateIncentive.ToString();
}

I have used decimal instead of double because the decimal type is more adapt to handle money values. 我使用小数而不是双数,因为小数类型更适合处理货币值。 I suggest to make the same change in the for..loop that fill the list (Just use the suffix m to specify constant decimal values (IE. 4.25m and 0.05m ) 我建议在for..loop中进行同样的更改以填充列表(只需使用后缀m来指定常数十进制值(即4.25m0.05m

You are trying to convert a currency string to double so you should Try like this: 您正在尝试将货币字符串转换为双精度,所以您应该这样尝试:

double stateIncentive = (Double.Parse(TotalPrice, System.Globalization.NumberStyles.Currency) / 4);

Or would be better if using decimal (Read this to know why): 或者使用decimal会更好(请阅读以下内容以了解原因):

decimal stateIncentive = (decimal.Parse(TotalPrice, System.Globalization.NumberStyles.Currency) / 4);

The style parameter defines the style elements (such as white space, thousands separators, and currency symbols) refer to MSDN: Double.Parse Method (String, NumberStyles) style参数定义了样式元素(例如空格,数千个分隔符和货币符号),请参阅MSDN: Double.Parse Method (String, NumberStyles)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM