2

I am working with the following question

Using system;
namespace StringToNumerics
{

    class Trial
    {

        static void Main(string[] args)
        {
            string division = "10/5";
            double divided = Convert.ToDouble(division);
            Console.WriteLine("divided {0} : ", divided);
            Console.ReadKey();
        }
    }
}

However I am given an error that the input string is not in the correct format? How to fix this.

System.FormatException: 'Input string was not in a correct format.'
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86

3 Answers3

3

What you are trying to do is basically convert that text into a double. It does not calculate it, it just tries to parse the numeric values and return them as a real number. To which, this returns an error, because the "/" sign is not understood by the converter.

Basically, what you have to do first, is parse your input string, tokenize it and then execute it.

So basically: split it into Operand1 (10), operator (/) and operand2 (5). Then convert the both operands and call an operation on it.

Oh, and don't froget to check for "division by zero" occurences.

DaMachk
  • 643
  • 4
  • 10
1

Its a string with "/" sign is not understood by the converter.

you need to split and then do it.

double divided = (Convert.ToDouble(division.Split('/')[0]) / Convert.ToDouble(division.Split('/')[1]));

Thennarasan
  • 698
  • 6
  • 11
0

Don't try to start from a string to compute something. It's easier to start with numbers, compute something and then produce a string output based on that.

static void Main(string[] args)
{
    double dividend = 10;
    double divisor = 5;
    double quotient = dividend / divisor;
    Console.WriteLine("divided {0}/{1} : {2}", dividend, divisor, quotient);
    Console.ReadKey();
}
Spotted
  • 4,021
  • 17
  • 33