Home > Mobile >  Why am I getting an incorrect input string error when I am trying to make currency calculations? C#
Why am I getting an incorrect input string error when I am trying to make currency calculations? C#

Time:10-04

I am trying to create a basic bank teller application where the balance ALWAYS starts out at $1000 and you can deposit and withdraw amounts. Currently, since the balance will always start at $1000, I have

public Form1()
    {
        InitializeComponent();

        lblBalance.Text = "1000.00";
        
    }

in the initializer, since it will always start out at 1000, and then I have

private void btnWithdraw_Click(object sender, EventArgs e)
       
        //Withdraw button, initializing variables to make withdrawal calculation based on current balance and what input is in withdrawal text box.

    {
        decimal withdraw = Decimal.Parse(txtWithdraw.Text);
        decimal INaccountBalance = Decimal.Parse(lblBalance.Text);
        decimal FINaccountBalance = (INaccountBalance - withdraw);

        lblBalance.Text = FINaccountBalance.ToString("c");
        
        
    }

on the withdraw button click, which is a calculation that just updates the balance based on what the current balance is in the label subtracted by whatever input is put into the text box for withdrawal, however my program crashes if i try to withdraw more than twice. So I can put 1 value in for the withdrawal and it will do the calculation and update the balance, but if I withdraw again it will just crash the program and give me an 'Input string was not in a correct format.' Error.

CodePudding user response:

It seems, you can't Parse currency format:

  lblBalance.Text = FINaccountBalance.ToString("c");

which returns to lblBalance.Text something like

  123.00$

(note currency sign $) and this string can't be Parsed again (you have FormatException thrown) into decimal on

  decimal INaccountBalance = Decimal.Parse(lblBalance.Text);

You can try changing format, say, into F2 - let the balance be with two digits after decimal point

  lblBalance.Text = FINaccountBalance.ToString("F2");

Now you are going to have decimal representation without currency signs

  123.00

which can be Parsed on the next withdrawal

CodePudding user response:

You can use an overload of Parse that accepts this

decimal INaccountBalance = Decimal.Parse(lblBalance.Text, NumberStyles.Any, null);

Or

decimal INaccountBalance = Decimal.Parse(lblBalance.Text, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint, null);
  • Related