0

The given given fields are, price, currency and formula where I need to read the formula and replace where the price and currency will go into, example:

(((Price+12,9)+((Price+12,9)*0,05)+(((Price+12,9)+((Price+12,9)*0,05))*0,029)+0,45)*Currency)+(2*Currency)

So in order to make the above I am doing:

string formula = iFormula.Text.Replace("Price", price.ToString("n2")).Replace("Currency", currency.ToString("n2"));

Since I want to make sure price and currency are correctly formatted, they are prior to replacement parsed into decimals.

Now here is where I am having problem with, how can I confirm that the formula is valid, and get the result of it ?

Is there a library that evaluate and compute the formula ?

Guapo
  • 3,446
  • 9
  • 36
  • 63
  • There are many duplicates. I'm too lazy to figure out which one is the best fit, but http://stackoverflow.com/questions/355062/is-there-a-string-math-evaluator-in-net is one of them. – CodesInChaos Jul 01 '12 at 20:43
  • I'd look into [NCalc](http://ncalc.codeplex.com/) – CodesInChaos Jul 01 '12 at 20:43
  • @CodeInChaos thank you, checking on it, I was actually using bad terms to search for this, so I had poorly questions results which didn't lead me to a good answer. – Guapo Jul 01 '12 at 21:00

2 Answers2

1

The open-source library Vici Core (part of Vici Project) contains an expression parser that allows you to parse and evaluate expressions at runtime. It's open source.

Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
0

There is no function like Javascript's eval in .NET BCL.

You can however to create a file in C# containing the needed function (it's simple), compile it (look at Microsoft's howto for the instructions), run the obtained executable and get the result. Compilation error means that the formula is wrong, you will get the error message and position from the compilation step.

Vlad
  • 35,022
  • 6
  • 77
  • 199