float.TryParse无法正常工作

时间:2017-09-13 21:45:08

标签: c#

我创建了计算货币汇率的程序。 该计划有:

  1. ComboboxCurrencyName - 显示货币名称。
  2. ComboCurrencyValue - 显示给定货币的价值。
  3. txtYourValue - 从用户那里获得金额的文本框
  4. 使用用户提供的金额计算给定货币汇率的按钮。
  5. 我的代码:

    public void EchangeRate(float x,float y)
    {
        label1.Text = (x * y).ToString();
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        if(comboCurrencyName.SelectedIndex==comboCurrencyValue.SelectedIndex)
        {
            float currency;
            float inputValue;
            if(float.TryParse(comboCurrencyValue.SelectedItem.ToString(),out currency)&& float.TryParse(txtYourValue.Text,out inputValue))
            {
                EchangeRate(currency,inputValue);
            }
        }
        else
        {
            MessageBox.Show("Not selected currency ");
        }
    }
    

    当我使用组合框选择给定货币并且我输入要转换的值时,按下按钮时没有任何反应。我认为这是将组合框转换为浮动值的问题。

    之前我使用float.Parse()我遇到了错误:

      

    System.FormatException:'输入字符串格式无效。

    Breakpoint

    Application window

1 个答案:

答案 0 :(得分:2)

替换为:

(float.TryParse(comboCurrencyValue.SelectedItem.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture,out currency)&& float.TryParse(txtYourValue.Text,out inputValue)) 

要解释:在波兰,使用逗号而不是小数点,因此您必须指定要使用不变文化。