0

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?

Annoying Bot
  • 359
  • 1
  • 5
  • 13
  • 1
    What does whole string must be calculated mean ? What are the contents of the string ? Can you provide a sample – V4Vendetta Sep 26 '12 at 12:21
  • What specifically doesn't work? The conversion, the output text? What do you type in the textbox1? – Steve Sep 26 '12 at 12:22
  • Is the textBox1.Text just one value (like '100')? Or is it infact a whole calculation (like '100+4*12'). If its the latter, then you'd first have to parse the string to work out each calculation. Or, perhaps preferably, grab the input earlier, so when the user types '100' and then clicks '+' you could pull in the '100' convert it to a decimal, and store that an addition is about to occur – HaemEternal Sep 26 '12 at 12:24
  • I am guessing he's building up an expression in the textbox like 1+2-3 and when the user types = he wants it to evaluate. OP? – n8wrl Sep 26 '12 at 12:25
  • If the string for example contains "1*3+6-2". The answer to that must be calculated and putted in a decimal. – Annoying Bot Sep 26 '12 at 12:25
  • I would say that your going to need to use Regex with something like this, in order to look for patterns – Derek Sep 26 '12 at 12:28
  • 1
    Perhaps you could find in [this question and accepted answer](http://stackoverflow.com/questions/11593128/mathematical-expressions-parser) a good starting point with Mathematical Expression Parser. – Steve Sep 26 '12 at 12:28

2 Answers2

0

Although your question is not clear. But if u want to display in the textbox you should convert it to string.

private void btn_enter_Click(object sender, EventArgs e)
{
    decimal answer;
    answer = Convert.ToDecimal(textBox1.Text);

    textBox1.Text += "=" + answer.toString();
}
Leri
  • 12,367
  • 7
  • 43
  • 60
Amish Kumar
  • 259
  • 1
  • 3
  • 20
-1

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):

Expression e = new Expression("2 + 3 * 5");
Debug.Assert(17 == e.Evaluate());

You could replace the constructor of the Expression class with the text from your TextBox and then pipe the result of the call to Evaluate to wherever you want to output it to:

Expression e = new Expression(textBox1.Text);
MessageBox.Show(e.Evaluate().ToString());
Community
  • 1
  • 1
casperOne
  • 73,706
  • 19
  • 184
  • 253