0

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
H H
  • 263,252
  • 30
  • 330
  • 514
Trương Anh
  • 145
  • 1
  • 7
  • @Rob I do not think that is the short way the OP is thinking of :) – Brian Ogden May 07 '17 at 03:59
  • 5
    No there is no short way to do this, you have to parse the string or present a user interface that allows someone to type numbers and press a log, substract, add button, aka a calculator interface than you do not have to parse a string at all – Brian Ogden May 07 '17 at 04:00
  • You can check this post http://stackoverflow.com/questions/333737/evaluating-string-342-yield-int-18 – hardkoded May 07 '17 at 04:10
  • 2
    Hmm, that duplicate is outdated and also closed, as a dupe of a question that asks specifically for _compilation_. I think this deserves a fresh start. Reopening. – H H May 07 '17 at 04:36
  • @HenkHolterman I dunno, answers for this question will be people either suggesting their favorite lexing/parsing libraries or suggesting that OP write his own. Either way, I'd agree with the question getting closed. – Abion47 May 07 '17 at 05:11

2 Answers2

7

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

1

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");
Community
  • 1
  • 1
inquisitive
  • 3,549
  • 2
  • 21
  • 47
  • 2
    Yes, but DataTable is limited and unavailable in dotnet core. – H H May 07 '17 at 04:37
  • It works well with double number and "+ - * /" operator. But It doesn't work with Log. I get it a exception like this: Unhandled Exception: System.Data.EvaluateException: The expression contains undefined function call Log(). – Trương Anh May 08 '17 at 12:19