Reputation: 53
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.
Upvotes: 1
Views: 160
Reputation: 460108
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.
Upvotes: 8