Igzo
Igzo

Reputation: 57

how to evaluate ( math ) a string expression, vb.net

I'm not sure the term I used is correct. but I have a string expression and I want it to be calculated. this an example

Dim S = "4+4"
dim result = evaluate(S) 'some sort of treatment // that return 8

I'm not sure how this is going to work. I'm familiar with the JS eval function. but it seems that I need to add some sort of a library. and I don't want to do that. I have found some links about using

dim s = new expression("4+4") 

and getting the result with

s.evaluate()

but that require to add another library. and as I said before I don't want to use any library. I just want a solution on how to proceed? I have hit a wall. BTW I'm still a beginner try to answer as simple as you can I would appreciate it.

Upvotes: 2

Views: 2686

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

You can use the DataTable.Compute-"trick":

Dim tbl = new DataTable()
Dim result = Convert.ToDouble(tbl.Compute("4+4", Nothing))

The following arithmetic operators are supported in expressions:

+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus)

More informations: DataColumn.Expression at Expression Syntax.

Upvotes: 7

Related Questions