Input string was not in a correct format, “double.parse(textbox.text);”

后端 未结 4 1189
栀梦
栀梦 2021-01-28 10:45

Hi am quite new to visual studios.

This is my code so far to make an example of an atm, i have a text box and i put an amount in and then i have this button where i clic

4条回答
  •  执念已碎
    2021-01-28 11:31

    You can't trust your user to type exactly a double value in your textbox.
    The Parse method cannot avoid an exception if the input cannot be converted to a double.
    Instead the double.TryParse methods give the chance to test if the value typed is effectively a double. Also it seems that you are working with currency values, so perhaps it is better to use a decimal data type and when building the output string use the appropriate formatting to get a correct currency string for your locale. This will also avoid rounding errors intrinsically present in the double/single datatype

    private decimal totalamount = 0;
    public string balance1;
    
    private void buttoncredit_Click(object sender, RoutedEventArgs e)
    {
        decimal temp;
        if(decimal.TryParse(textboxamount.Text, out temp))
        {
            totalamount = totalamount + temp;
            balance1 = "Your Balance is: ";
            label2.Content = balance1 + totalamount.ToString("C");    
            textboxamount.Clear();
    
        }
        else
            MessageBox.Show("Not a valid amount");
    }
    
    private void buttondebit_Click(object sender, RoutedEventArgs e)
    {
        decimal temp;
        if(decimal.TryParse(textboxamount.Text, out temp))
        {
            if (totalamount - temp < 0)
            {
                 MessageBox.Show("Overdraft Limit is not set please contact Customer Services");
            }
            else
            {
                 totalamount = totalamount - temp;
                 balance1 = " Your Balance is: ";
                 label2.Content = balance1 + totalamount.ToString("C");
                 textboxamount.Clear();
            }
        }
        else
            MessageBox.Show("Not a valid amount");
    }
    

提交回复
热议问题