简体   繁体   中英

C#, How to compute an operation string

i have a string like that

str = "4975 + 10 * (LOG(250.6)) - 321.2"

i want to compute the result of this operation. Is there any sort way to do that?

// my operation just includes some of operators (,), +, -, *, / , ., 0-9, LOG
// '.' is used for double number

I believe this is what you are looking for.

Use this library will help you to perform math operations in string format

Add this package

Install-Package DynamicExpresso.Core

code example

public static void Main(string[] args)
        {
            var interpreter = new Interpreter();
            var result = interpreter.Eval("4975 + 10 * (LOG(250.6)) - 321.2".Replace("LOG", "Math.Log"));

            Console.WriteLine("result=> " + result);
            Console.ReadKey();
        }

result=> 4709.03858042462

link for lib https://github.com/davideicardi/DynamicExpresso

Also answered here:

https://stackoverflow.com/a/2859130/1043824

Try DataTable.Compute

I do not have a .net box lying around so I cannot confirm whether it can do log or not, but I have used it for long algebric expressions.

Basically this is how it goes:

DataTable dt = new DataTable();
var ans = dt.compute("5 + (7 - 9) / 3");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM