0

I'm trying to calculate the content of the string.

I've got 1 string which contains for example: MyString = "1+5/2*4-2" now I want to calculate the result of that string

I'm by the way new to c#

my code:

string som = "";
int myInt; 

private void getText_Click(object sender, EventArgs e)
{
    string s = (sender as Button).Text;
    som = som + s;
    Console.WriteLine(som);
    string[] words = som.Split(' ');

    foreach (string word in words)
    {
        Console.WriteLine(word);

        myInt += Convert.ToInt32(word);
    }

    Console.WriteLine(myInt);

I've tried this answer:

 double result = (double) new DataTable().Compute("1+1*4/2-5", null);
 int i = (int) result;  // -2

But then i get an System.InvalidCastException:

Specified cast is not valid.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Debialo
  • 43
  • 11
  • 1
    Have a look at my answer here: https://stackoverflow.com/questions/355062/is-there-a-string-math-evaluator-in-net/36156299#36156299 – Crowcoder Sep 20 '17 at 11:56
  • 1
    Possible duplicate of [Is there a string math evaluator in .NET?](https://stackoverflow.com/questions/355062/is-there-a-string-math-evaluator-in-net) – Fildor Sep 20 '17 at 12:37
  • _"But then i get an System.InvalidCastException:"_ Where did you get this exception? Bost casts in your code at the end of the question are valid, so i wonder where you got the exception at all. Or what was the string that you actually passed to `Compute`? You can evaluate the `Compute` call in the debugger, then you can inspect the rtesult and it's type in the debugger window and you know what you should cast it to instead(iof the exception was really raised at this line). – Tim Schmelter Sep 21 '17 at 07:38

1 Answers1

8

You can use the DataTable.Compute - "trick":

 double result = (double) new DataTable().Compute("1+1*4/2-5", null);
 int i = (int) result;  // -2

Syntax and supported operators are mentioned under Remarks here.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939