1

I am trying to convert string to perform arithmetic expression but getting format expression. I want the expression to be calculated and final answer.

// original value
     string text = @"4'-8"x5/16"x20'-8 13/16";

                string path = text.Replace("'", "*12").Replace("-", "+").Replace("x", "+").Replace(" ", "+").Replace(@"""", "");
                System.Console.WriteLine("The original string: '{0}'", text);
                System.Console.WriteLine("The final string: '{0}'", path);

                    Console.WriteLine();

                    decimal d = decimal.Parse(path, CultureInfo.InvariantCulture);
                    Console.WriteLine(d.ToString(CultureInfo.InvariantCulture));

// after converting got this value in debug
//'4*12+8+5/16+20*12+8+13/16'
9
  • What's the precise exception and on which line do you get it Commented Apr 17, 2017 at 14:54
  • Using decimal.Parse is not going to evaluate a mathematical expression stored in a string. It doesn't work that way. You're going to have to extract the operands and do the math in your code. Commented Apr 17, 2017 at 14:54
  • decimal d = decimal.Parse(path, CultureInfo.InvariantCulture); Commented Apr 17, 2017 at 14:54
  • why are you converting the "x5/16" to + 5/16"? Commented Apr 17, 2017 at 14:55
  • x should be converted to + and then added to the final value. Commented Apr 17, 2017 at 14:57

2 Answers 2

4

You can use the DataTable class to evaluate a mathematical expression string, using the Compute() method, passing a String.Empty as the second parameter.

var parsingEngine = new DataTable(); //in System.Data
int i = (int)parsingEngine.Compute("3 + 4", String.Empty);
decimal d = (decimal)parsingEngine.Compute("3.45 * 76.9/3", String.Empty);

Just be aware that Compute returns an object, and you must be careful to cast it to an appropriate type based on what your mathematical expression should yield.

Sign up to request clarification or add additional context in comments.

4 Comments

getting error as: Specified cast is not valid. var parsedvalue = new DataTable(); int i = (int)parsedvalue.Compute(path, String.Empty); decimal d = (decimal)parsedvalue.Compute(path, String.Empty);
Like I said, the casting can be difficult because Compute elects the type based on the data. It will assuredly be either an integer, double, or decimal. You can use "is", or GetType() to determine the type dynamically. eg, object o = parsingEngine.Compute(myexprSTR, String,Empty); if(o is int) cast as int; else if(o is decimal) cast as decimal; else if (o is double) cast as double; etc. It is also important to use expressions with proper supported symbols, ie '*' not 'x', '/' not '÷' etc. You cant use any string that COULD be math, you must use one that conforms to a subset of tradition.
if that still doesn't work, just print out GetType()'s return value, and it will apprise you of what Compute has encoded. Additionally, the two expressions in my answer, and their casts, are valid examples to help point you in the right direction.
The issue with the return of an object is easily taken care of by using System.Convert. So instead of casting you use decimal d = System.Convert.ToDecimal(parseEngine.Compute(...));
0

Unfortunately .NET does not have anything built in that will evaluate a mathematical expression string. You'll need to use a third party library like NCalc.

Then you can use it in your code like this

// original value
//string text = System.IO.File.ReadAllText(@"4'-8"x5/16"x20'-8 13/16"); This needs to be a filepath.
string text = @"4'-8x5/16x20'-8 13/16";

string path = text.Replace("'", "*12").Replace("-", "+").Replace("x", "+").Replace(" ", "+").Replace(@"""", "");
System.Console.WriteLine("The original string: '{0}'", text);
System.Console.WriteLine("The final string: '{0}'", path);

Expression e = new Expression(path)
Console.WriteLine(e.Evaluate);

5 Comments

Also File.ReadAllText needs a file path...it's taking the OPs math expression
I removed the portion throwing the expression. I left the incorrect File.ReadAllText from OP's answer since I'm assuming he or she put that in place to show us an example of expected text input. Even though it is formatted incorrectly....
.NET does have something that will evalueate a mathematical expression string, the DataTable. See my answer below.(about to write it)
@JoshuaHysong EDIT: Answer Written
@shulmaster that is very clever! Learned something new today =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.