I want to evaluate a math expression which the user enters in a textbox. I have done this so far
string equation, finalString;
equation = textBox1.Text;
StringBuilder stringEvaluate = new StringBuilder(equation);
stringEvaluate.Replace("sin", "math.sin");
stringEvaluate.Replace("cos", "math.cos");
stringEvaluate.Replace("tan", "math.tan");
stringEvaluate.Replace("log", "math.log10");
stringEvaluate.Replace("e^", "math.exp");
finalString = stringEvaluate.ToString();
StringBuilder replaceI = new StringBuilder(finalString);
replaceI.Replace("x", "i");
double a;
for (int i = 0; i<5 ; i++)
{
a = double.Parse(finalStringI);
if(a<0)
break;
}
when I run this program it gives an error "Input string was not in a correct format." and highlights a=double.Parse(finalStringI);
I used a pre defined expression a=i*math.log10(i)-1.2 and it works, but when I enter the same thing in the textbox it doesn’t.
I did some search and it came up with something to do with compiling the code at runtime.
any ideas how to do this?
i’m an absolute beginner.
thanks 🙂
The issue is within your
stringEvaluateStringBuilder. When you’re replacing “sin” with “math.sin”, the content withinstringEvaluateis still a string. You’ve got the right idea, but the error you’re getting is because of that fact.Math.sinis a method inside theMathclass, thus it cannot be operated on as you are in youra = double.Parse(finalStringI);call.It would be a pretty big undertaking to accomplish your goal, but I would go about it this way:
solution.StringBuilderclass. For example, if you encounter a “sin”, addMath.sinto the operator collection (of which I’d use type object).Hope this helps 🙂