I’m trying to program a calculator in which the buttons send a character to a textbox. When the user presses the “equals” button, the whole string must be calculated and the answer must be displayed as a decimal. Obviously the following doesn’t work:
private void btn_enter_Click(object sender, EventArgs e)
{
decimal answer;
answer = Convert.ToDecimal(textBox1.Text);
textBox1.Text += "=" + answer;
}
What is the best way to make something like this works?
You could go along the lines of evaluating C# on the fly, but for what you’re trying to do, it’s a bit overkill.
I’d recommend a calculation engine, like NCalc (which you can get on NuGet). With it, you can easily do something like (taken from the NCalc homepage):
You could replace the constructor of the
Expressionclass with the text from yourTextBoxand then pipe the result of the call toEvaluateto wherever you want to output it to: