Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to convert a string with mathematical expression into decimal 1

Status
Not open for further replies.

mondi

Programmer
Sep 10, 2003
169
AL
Hi to all!
I have a string that contains a mathematical expression e.g. "(5 + 2) * 3 + 1". I want to get the decimal value that this expression gives. The expression might not be this one (it is stored in the database as a string). It might be longer than this. The biggest problem I think is the brackets. Is there some way in C# to do that?
I hope I was clear and you understood my question!
Thanks in advance for any help!

Country of eagles
 
There may well be a better answer, but have a look at using the VBScript object from the Windows Scripting Host - it contains a function called Eval, which will do exactly what you need.


Hope this helps.

[vampire][bat]
 
Thanks earthandfire for your answer. I found an interesting source code that gave an answer to my problem at codeproject. I think I am going to see what he has done and try it.

Country of eagles
 
I like earthandfire's idea.
code from
Code:
using System;

namespace Eval
{
    class Program
    {
        static void Main(string[] args)
        {
            string strcomp; object obresult; double result;
            result = (5 + 2) * 3 + 1;
            Console.WriteLine(result);
            strcomp = "(5 + 2) * 3 + 1";
            MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
            sc.Language = "VBScript";
            obresult = sc.Eval(strcomp);
            Console.WriteLine(obresult.ToString());
        }
    }
}
Marty
 
There are two or three source code alternatives that I found on CodeProject that I have tried out over the last couple of years, but none as easy to use or as intuitive as Eval, as demonstrated by Marty's solution.

Hope this helps.

[vampire][bat]
 
Thanks both of you, will have a further look at Marty's idea. Yes me too I think is a better solution!
Thanks again!

Country of eagles
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top