-3

I'm trying to make a simple calculator and its fully working but when I calculate without a = button, my program completely crashes and gives the error:

System.FormatException: 'Input string was not in correct format.'

This is the code that it throws an error to:

second = double.Parse(aNumber);
// the strings and doubles:

String aNumber = "";
double first = 0.0;
  • Show us more code. What is `second`? How are you getting the user's value. – Frontear Nov 20 '18 at 18:00
  • Yes, "" causes an exception. You can a) test for "" beforehand, or b) catch the exception. – Mr Lister Nov 20 '18 at 18:04
  • double second = 0.0; – Pride UK Nov 20 '18 at 18:14
  • Or use double.TryParse if it is not sure that aNumber is really the string representation of a number. – Klaus Gütter Nov 20 '18 at 18:16
  • 3
    You need to learn [how to debug](http://idownvotedbecau.se/nodebugging/). Then learn [`Double.TryParse`](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=netframework-4.7.1#System_Double_TryParse_System_String_System_Double__). – Dour High Arch Nov 20 '18 at 18:16
  • 1
    Possible duplicate of [Input string was not in a correct format](https://stackoverflow.com/questions/8321514/input-string-was-not-in-a-correct-format) –  Nov 20 '18 at 18:20

2 Answers2

0

b will be true or false if the try parse worked d will contain the double or 0 if it fails change anum to a valid number to test.

String anum = "";
double d    = 0.0;
bool b      = double.TryParse(anum, out d);
dcarl661
  • 177
  • 3
  • 9
0

double.Parse will throw an exception if the input is not valid. So you either need to use try catch - or the preferred way would be to use double.TryParse as below. The value of y below will be set to the value if TryParse returns true.

class Program
{
    static void Main(string[] args)
    {
        // This will cause an exception 
        var someString = "SomeValue"; 
        var x = double.Parse(someString);  // Comment this line out to run this example

        // This will work 
        double y;
        if (double.TryParse(someString, out y))
        {
            Console.WriteLine(someString + " is a valid decimal");
        }
        else
        {
            Console.WriteLine(someString + " is not a valid decimal");
        }

        someString = "14.7";
        if (double.TryParse(someString, out y))
        {
            Console.WriteLine(someString + " is a valid decimal");
        }
        else
        {
            Console.WriteLine(someString + " is not a valid decimal");
        }
    }
}
Jon Vote
  • 604
  • 5
  • 17