FormatException: Input string was not in a correct format

Hello,
I’m trying to make an exchange system between two currencies (int, float)

Here’s my code for the exchange button:

public void OnExchange()
    {
        int currGems = Session.Balance_Gem;
        float currDollars = Session.Balance_USD;


        if (Session.Balance_Gem >= GemsToExchange)
        {
            currGems -= GemsToExchange;
            currDollars += float.Parse(Dollars_INPUT.text.ToString());
            Session.Balance_Gem = currGems;
            Session.Balance_USD = currDollars;
            Session.Instance.CallSaveData("USD_Balance");
            Session.Instance.CallSaveData("USD_Gem");


        }
        else
        {
            NativeUI.ShowToast("Unfortunately, Your gems(" + Session.Balance_Gem + ") are insufficient!");
        }
    }

I’m getting an error:

FormatException: Input string was not in a correct format.
System.Number.ParseSingle (System.String value, System.Globalization.NumberStyles options, System.Globalization.NumberFormatInfo numfmt) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Single.Parse (System.String s, System.Globalization.NumberStyles style, System.Globalization.NumberFormatInfo info) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Single.Parse (System.String s) (at <695d1cc93cca45069c528c15c9fdd749>:0)
WalletManager.OnExchange () (at Assets/TheWallet/Scripts/WalletManager.cs:133)


is there any chances i can fix it

My guess is you’re putting something like _**33.50**_ as an input value and then the parse fails because of the __**__. You should try to clean up the string yourself first by removing extra characters, and then parse. Also wrap your code in a try/catch block or use TryParse instead which returns a boolean result instead of throwing exceptions.

1 Like