Parse Math ExpressionHow would I manually (no third-party libraries) evaluate an equation from a string in C#?Double.TryParse doesn't allow to use divisions (fractions) as inputC# - Load Mathematical FormulaConvert string into mathematical expressionFunction of count / process a series of combination numbers and math operations ('+', '-', '*", '/')Equation (expression) parser with precedence?Is there a string math evaluator in .NET?operators as stringsBest Free C# Math Parser using variables, user defined functions, custom operatorsDoing math in vb.net like Eval in javascriptBest way to parse command line arguments in C#?Replacing .NET WebBrowser control with a better browser, like Chrome?Parse JSON in C#Reflecting parameter name: abuse of C# lambda expressions or Syntax brilliance?Boolean and Math Expression ParserSimple state machine example in C#?Curious null-coalescing operator custom implicit conversion behaviourWhy is processing a sorted array slower than an unsorted array?Why not inherit from List<T>?Found conflicts between different versions of the same dependent assembly that could not be resolved

What is Plautus’s pun about frustum and frustrum?

Why was Thor doubtful about his worthiness to Mjolnir?

Surely they can fit?

How to make a language evolve quickly?

How to compact two the parabol commands in the following example?

How does noise-cancellation work in Mac laptops?

How to minimise the cost of guessing a number in a high/low guess game?

Python Pandas Expand a Column of List of Lists to Two New Column

Why do Thanos's punches not kill Captain America or at least cause some mortal injuries?

How did Thanos not realise this had happened at the end of Endgame?

Why doesn't Rocket Lab use a solid stage?

How to select certain lines (n, n+4, n+8, n+12...) from the file?

Usefulness of complex chord names?

Should these notes be played as a chord or one after another?

Why was Endgame Thanos so different than Infinity War Thanos?

Ex-manager wants to stay in touch, I don't want to

Anatomically Correct Carnivorous Tree

How to slow yourself down (for playing nice with others)

As programers say: Strive to be lazy

Is it a bad idea to replace pull-up resistors with hard pull-ups?

How can dragons propel their breath attacks to a long distance

What does "Ich wusste, dass aus dir mal was wird" mean?

What happens if a creature that would fight isn't on the battlefield anymore?

A cryptic tricolour



Parse Math Expression


How would I manually (no third-party libraries) evaluate an equation from a string in C#?Double.TryParse doesn't allow to use divisions (fractions) as inputC# - Load Mathematical FormulaConvert string into mathematical expressionFunction of count / process a series of combination numbers and math operations ('+', '-', '*", '/')Equation (expression) parser with precedence?Is there a string math evaluator in .NET?operators as stringsBest Free C# Math Parser using variables, user defined functions, custom operatorsDoing math in vb.net like Eval in javascriptBest way to parse command line arguments in C#?Replacing .NET WebBrowser control with a better browser, like Chrome?Parse JSON in C#Reflecting parameter name: abuse of C# lambda expressions or Syntax brilliance?Boolean and Math Expression ParserSimple state machine example in C#?Curious null-coalescing operator custom implicit conversion behaviourWhy is processing a sorted array slower than an unsorted array?Why not inherit from List<T>?Found conflicts between different versions of the same dependent assembly that could not be resolved






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








8















Is there an easy way to parse a simple math expression represented as a string such as (x+(2*x)/(1-x)), provide a value for x, and get a result?



I looked at the VSAEngine per several online examples, however, I am getting a warning that this assembly has been deprecated and not to use it.



If it makes any differences, I am using .NET 4.0.










share|improve this question
























  • I posted full source for this problem here: stackoverflow.com/questions/174664/operators-as-strings

    – Austin Salonen
    Oct 19 '10 at 22:08











  • possible duplicate of Is it possible to compile and execute new code at runtime in .NET?

    – nawfal
    May 31 '13 at 16:23











  • possible duplicate of Is there a string math evaluator in .NET?

    – Robert MacLean
    Oct 15 '14 at 13:13

















8















Is there an easy way to parse a simple math expression represented as a string such as (x+(2*x)/(1-x)), provide a value for x, and get a result?



I looked at the VSAEngine per several online examples, however, I am getting a warning that this assembly has been deprecated and not to use it.



If it makes any differences, I am using .NET 4.0.










share|improve this question
























  • I posted full source for this problem here: stackoverflow.com/questions/174664/operators-as-strings

    – Austin Salonen
    Oct 19 '10 at 22:08











  • possible duplicate of Is it possible to compile and execute new code at runtime in .NET?

    – nawfal
    May 31 '13 at 16:23











  • possible duplicate of Is there a string math evaluator in .NET?

    – Robert MacLean
    Oct 15 '14 at 13:13













8












8








8


8






Is there an easy way to parse a simple math expression represented as a string such as (x+(2*x)/(1-x)), provide a value for x, and get a result?



I looked at the VSAEngine per several online examples, however, I am getting a warning that this assembly has been deprecated and not to use it.



If it makes any differences, I am using .NET 4.0.










share|improve this question
















Is there an easy way to parse a simple math expression represented as a string such as (x+(2*x)/(1-x)), provide a value for x, and get a result?



I looked at the VSAEngine per several online examples, however, I am getting a warning that this assembly has been deprecated and not to use it.



If it makes any differences, I am using .NET 4.0.







c# .net c#-4.0






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 30 '13 at 15:26









Steve Konves

2,17732041




2,17732041










asked Oct 19 '10 at 21:19









BrandonBrandon

4,947135693




4,947135693












  • I posted full source for this problem here: stackoverflow.com/questions/174664/operators-as-strings

    – Austin Salonen
    Oct 19 '10 at 22:08











  • possible duplicate of Is it possible to compile and execute new code at runtime in .NET?

    – nawfal
    May 31 '13 at 16:23











  • possible duplicate of Is there a string math evaluator in .NET?

    – Robert MacLean
    Oct 15 '14 at 13:13

















  • I posted full source for this problem here: stackoverflow.com/questions/174664/operators-as-strings

    – Austin Salonen
    Oct 19 '10 at 22:08











  • possible duplicate of Is it possible to compile and execute new code at runtime in .NET?

    – nawfal
    May 31 '13 at 16:23











  • possible duplicate of Is there a string math evaluator in .NET?

    – Robert MacLean
    Oct 15 '14 at 13:13
















I posted full source for this problem here: stackoverflow.com/questions/174664/operators-as-strings

– Austin Salonen
Oct 19 '10 at 22:08





I posted full source for this problem here: stackoverflow.com/questions/174664/operators-as-strings

– Austin Salonen
Oct 19 '10 at 22:08













possible duplicate of Is it possible to compile and execute new code at runtime in .NET?

– nawfal
May 31 '13 at 16:23





possible duplicate of Is it possible to compile and execute new code at runtime in .NET?

– nawfal
May 31 '13 at 16:23













possible duplicate of Is there a string math evaluator in .NET?

– Robert MacLean
Oct 15 '14 at 13:13





possible duplicate of Is there a string math evaluator in .NET?

– Robert MacLean
Oct 15 '14 at 13:13












9 Answers
9






active

oldest

votes


















5














You can try using DataTable.Compute.



A related one is DataColumn.Expression.



Also check out: Doing math in vb.net like Eval in javascript



Note: I haven't used these myself.






share|improve this answer

























  • Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.

    – Brandon
    Oct 20 '10 at 16:44


















10














I urge caution against choosing an existing generic expression evaluator over a purpose-built math evaluator. The reason for this is that the expression evaluators are not limited to just math. A clever individual could use this to create an instance of any type in the framework and call any method on the type, and that would allow him to do some decidedly unwelcome things. For example: new System.Net.WebClient().DownloadFile("illegalchildpornurl", "C:openme.gif") will evaluate just fine in most of those, and do just what it sounds like it would (and make you a felon at the same time).



This doesn't mean don't look for something that's already written. It just means be careful. You want one that does math, and only math. Most of what's already out there isn't that picky.






share|improve this answer
































    8














    I was recently using mXparser, which is a math parser library. It gives you a lot of flexibility, such as variables, functions, constants, operators. You will find below a few usage examples:



    Example 1 - simple formula



    Expression e = new Expression("1 + pi");
    double v = e.calculate();


    Example 2 - formula with variables, functions, etc.



    Argument x = new Argument("x = 2");
    Constant a = new Constant("a = sin(10)");
    Function f = new Function("f(t) = t^2");
    Expression e = new Expression("2*x + a - f(10)", x, a, f);
    double v = e.calculate();


    https://mxparser.codeplex.com/



    http://mathparser.org/



    Found recntly - you can try the syntax (and see the use case) via the Scalar Calculator app that is powered by mXparser.



    Best regards



    Best regards






    share|improve this answer
































      3














      I would also have a look at Jace (https://github.com/pieterderycke/Jace). Jace is a high performance math parser and calculation engine that supports all the .NET flavors (.NET 4.x, Windows Phone, Windows Store, ...). Jace is also available through NuGet: https://www.nuget.org/packages/Jace






      share|improve this answer






























        2














        Here is one way to do it. This code is written in Java. Note it does not handle negative numbers right now, but you can add that.



        public class ExpressionParser 
        public double eval(String exp, Map<String, Double> vars)
        int bracketCounter = 0;
        int operatorIndex = -1;

        for(int i=0; i<exp.length(); i++)
        if(operatorIndex < 0)
        exp = exp.trim();
        if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')')
        return eval(exp.substring(1, exp.length()-1), vars);
        else if(vars.containsKey(exp))
        return vars.get(exp);
        else
        return Double.parseDouble(exp);

        else
        switch(exp.charAt(operatorIndex))
        case '+':
        return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars);
        case '-':
        return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars);
        case '*':
        return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars);
        case '/':
        return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars);


        return 0;





        You need to import java.util.Map.



        Here is how I use this code:



         ExpressionParser p = new ExpressionParser();
        Map vars = new HashMap<String, Double>();
        vars.put("x", 2.50);
        System.out.println(p.eval(" 5 + 6 * x - 1", vars));





        share|improve this answer


















        • 1





          This is a beautiful piece of code. Thank you

          – Illishar
          Mar 16 '18 at 8:44











        • Thank you @Illishar

          – user4617883
          Mar 16 '18 at 16:01


















        1














        Another option you may want to look into is the Spring.NET Framework's expression evaluation functionality. It can do a lot more than math, too.



        However, the entire Spring.NET Framework might be a bit of overkill for your needs if you don't require the rest of the functionality.






        share|improve this answer






























          1














          Related: Equation expression parser with precedence.






          share|improve this answer
































            0














            As I answered in this thread (Best Free C# Math Parser using variables, user defined functions, custom operators), you can use Mathos Parser, which you can simply paste into your source code.



             Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser();

            string expr = "(x+(2*x)/(1-x))"; // the expression

            decimal result = 0; // the storage of the result

            parser.LocalVariables.Add("x", 41); // 41 is the value of x

            result = parser.Parse(expr); // parsing

            Console.WriteLine(result); // 38.95





            share|improve this answer

























            • Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.

              – Nic Foster
              Jun 12 '17 at 5:07











            • @NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.

              – Artem
              Jun 12 '17 at 7:39


















            0














            I recomend you to use MEEL for this.



            // parse string to IExpression (symbolic type)
            IExpression expression = BaseExpression.Parse("(x+(2*x)/(1-x))");

            // create your own collection for attributes
            var attributes = new MathAttributeCollection();
            // create local variable named "x" with value 5
            var attributeX = new ScalarAttrInt("x") Value = new ScalarConstInt(5);
            attributes.Add(attributeX);

            // execute math expression where x=5
            var result = expression.Execute(attributes);

            MessageBox.Show(result.GetText());
            // result: 2.5





            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3972854%2fparse-math-expression%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              9 Answers
              9






              active

              oldest

              votes








              9 Answers
              9






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              5














              You can try using DataTable.Compute.



              A related one is DataColumn.Expression.



              Also check out: Doing math in vb.net like Eval in javascript



              Note: I haven't used these myself.






              share|improve this answer

























              • Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.

                – Brandon
                Oct 20 '10 at 16:44















              5














              You can try using DataTable.Compute.



              A related one is DataColumn.Expression.



              Also check out: Doing math in vb.net like Eval in javascript



              Note: I haven't used these myself.






              share|improve this answer

























              • Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.

                – Brandon
                Oct 20 '10 at 16:44













              5












              5








              5







              You can try using DataTable.Compute.



              A related one is DataColumn.Expression.



              Also check out: Doing math in vb.net like Eval in javascript



              Note: I haven't used these myself.






              share|improve this answer















              You can try using DataTable.Compute.



              A related one is DataColumn.Expression.



              Also check out: Doing math in vb.net like Eval in javascript



              Note: I haven't used these myself.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 23 '17 at 11:47









              Community

              11




              11










              answered Oct 19 '10 at 21:28







              Aryabhatta



















              • Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.

                – Brandon
                Oct 20 '10 at 16:44

















              • Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.

                – Brandon
                Oct 20 '10 at 16:44
















              Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.

              – Brandon
              Oct 20 '10 at 16:44





              Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.

              – Brandon
              Oct 20 '10 at 16:44













              10














              I urge caution against choosing an existing generic expression evaluator over a purpose-built math evaluator. The reason for this is that the expression evaluators are not limited to just math. A clever individual could use this to create an instance of any type in the framework and call any method on the type, and that would allow him to do some decidedly unwelcome things. For example: new System.Net.WebClient().DownloadFile("illegalchildpornurl", "C:openme.gif") will evaluate just fine in most of those, and do just what it sounds like it would (and make you a felon at the same time).



              This doesn't mean don't look for something that's already written. It just means be careful. You want one that does math, and only math. Most of what's already out there isn't that picky.






              share|improve this answer





























                10














                I urge caution against choosing an existing generic expression evaluator over a purpose-built math evaluator. The reason for this is that the expression evaluators are not limited to just math. A clever individual could use this to create an instance of any type in the framework and call any method on the type, and that would allow him to do some decidedly unwelcome things. For example: new System.Net.WebClient().DownloadFile("illegalchildpornurl", "C:openme.gif") will evaluate just fine in most of those, and do just what it sounds like it would (and make you a felon at the same time).



                This doesn't mean don't look for something that's already written. It just means be careful. You want one that does math, and only math. Most of what's already out there isn't that picky.






                share|improve this answer



























                  10












                  10








                  10







                  I urge caution against choosing an existing generic expression evaluator over a purpose-built math evaluator. The reason for this is that the expression evaluators are not limited to just math. A clever individual could use this to create an instance of any type in the framework and call any method on the type, and that would allow him to do some decidedly unwelcome things. For example: new System.Net.WebClient().DownloadFile("illegalchildpornurl", "C:openme.gif") will evaluate just fine in most of those, and do just what it sounds like it would (and make you a felon at the same time).



                  This doesn't mean don't look for something that's already written. It just means be careful. You want one that does math, and only math. Most of what's already out there isn't that picky.






                  share|improve this answer















                  I urge caution against choosing an existing generic expression evaluator over a purpose-built math evaluator. The reason for this is that the expression evaluators are not limited to just math. A clever individual could use this to create an instance of any type in the framework and call any method on the type, and that would allow him to do some decidedly unwelcome things. For example: new System.Net.WebClient().DownloadFile("illegalchildpornurl", "C:openme.gif") will evaluate just fine in most of those, and do just what it sounds like it would (and make you a felon at the same time).



                  This doesn't mean don't look for something that's already written. It just means be careful. You want one that does math, and only math. Most of what's already out there isn't that picky.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Sep 20 '11 at 19:16

























                  answered Oct 19 '10 at 21:39









                  Joel CoehoornJoel Coehoorn

                  314k97498737




                  314k97498737





















                      8














                      I was recently using mXparser, which is a math parser library. It gives you a lot of flexibility, such as variables, functions, constants, operators. You will find below a few usage examples:



                      Example 1 - simple formula



                      Expression e = new Expression("1 + pi");
                      double v = e.calculate();


                      Example 2 - formula with variables, functions, etc.



                      Argument x = new Argument("x = 2");
                      Constant a = new Constant("a = sin(10)");
                      Function f = new Function("f(t) = t^2");
                      Expression e = new Expression("2*x + a - f(10)", x, a, f);
                      double v = e.calculate();


                      https://mxparser.codeplex.com/



                      http://mathparser.org/



                      Found recntly - you can try the syntax (and see the use case) via the Scalar Calculator app that is powered by mXparser.



                      Best regards



                      Best regards






                      share|improve this answer





























                        8














                        I was recently using mXparser, which is a math parser library. It gives you a lot of flexibility, such as variables, functions, constants, operators. You will find below a few usage examples:



                        Example 1 - simple formula



                        Expression e = new Expression("1 + pi");
                        double v = e.calculate();


                        Example 2 - formula with variables, functions, etc.



                        Argument x = new Argument("x = 2");
                        Constant a = new Constant("a = sin(10)");
                        Function f = new Function("f(t) = t^2");
                        Expression e = new Expression("2*x + a - f(10)", x, a, f);
                        double v = e.calculate();


                        https://mxparser.codeplex.com/



                        http://mathparser.org/



                        Found recntly - you can try the syntax (and see the use case) via the Scalar Calculator app that is powered by mXparser.



                        Best regards



                        Best regards






                        share|improve this answer



























                          8












                          8








                          8







                          I was recently using mXparser, which is a math parser library. It gives you a lot of flexibility, such as variables, functions, constants, operators. You will find below a few usage examples:



                          Example 1 - simple formula



                          Expression e = new Expression("1 + pi");
                          double v = e.calculate();


                          Example 2 - formula with variables, functions, etc.



                          Argument x = new Argument("x = 2");
                          Constant a = new Constant("a = sin(10)");
                          Function f = new Function("f(t) = t^2");
                          Expression e = new Expression("2*x + a - f(10)", x, a, f);
                          double v = e.calculate();


                          https://mxparser.codeplex.com/



                          http://mathparser.org/



                          Found recntly - you can try the syntax (and see the use case) via the Scalar Calculator app that is powered by mXparser.



                          Best regards



                          Best regards






                          share|improve this answer















                          I was recently using mXparser, which is a math parser library. It gives you a lot of flexibility, such as variables, functions, constants, operators. You will find below a few usage examples:



                          Example 1 - simple formula



                          Expression e = new Expression("1 + pi");
                          double v = e.calculate();


                          Example 2 - formula with variables, functions, etc.



                          Argument x = new Argument("x = 2");
                          Constant a = new Constant("a = sin(10)");
                          Function f = new Function("f(t) = t^2");
                          Expression e = new Expression("2*x + a - f(10)", x, a, f);
                          double v = e.calculate();


                          https://mxparser.codeplex.com/



                          http://mathparser.org/



                          Found recntly - you can try the syntax (and see the use case) via the Scalar Calculator app that is powered by mXparser.



                          Best regards



                          Best regards







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 23 at 11:55

























                          answered Mar 4 '16 at 21:47









                          Leroy KeganLeroy Kegan

                          57655




                          57655





















                              3














                              I would also have a look at Jace (https://github.com/pieterderycke/Jace). Jace is a high performance math parser and calculation engine that supports all the .NET flavors (.NET 4.x, Windows Phone, Windows Store, ...). Jace is also available through NuGet: https://www.nuget.org/packages/Jace






                              share|improve this answer



























                                3














                                I would also have a look at Jace (https://github.com/pieterderycke/Jace). Jace is a high performance math parser and calculation engine that supports all the .NET flavors (.NET 4.x, Windows Phone, Windows Store, ...). Jace is also available through NuGet: https://www.nuget.org/packages/Jace






                                share|improve this answer

























                                  3












                                  3








                                  3







                                  I would also have a look at Jace (https://github.com/pieterderycke/Jace). Jace is a high performance math parser and calculation engine that supports all the .NET flavors (.NET 4.x, Windows Phone, Windows Store, ...). Jace is also available through NuGet: https://www.nuget.org/packages/Jace






                                  share|improve this answer













                                  I would also have a look at Jace (https://github.com/pieterderycke/Jace). Jace is a high performance math parser and calculation engine that supports all the .NET flavors (.NET 4.x, Windows Phone, Windows Store, ...). Jace is also available through NuGet: https://www.nuget.org/packages/Jace







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jan 27 '14 at 8:19









                                  MuSTaNGMuSTaNG

                                  3,2372106




                                  3,2372106





















                                      2














                                      Here is one way to do it. This code is written in Java. Note it does not handle negative numbers right now, but you can add that.



                                      public class ExpressionParser 
                                      public double eval(String exp, Map<String, Double> vars)
                                      int bracketCounter = 0;
                                      int operatorIndex = -1;

                                      for(int i=0; i<exp.length(); i++)
                                      if(operatorIndex < 0)
                                      exp = exp.trim();
                                      if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')')
                                      return eval(exp.substring(1, exp.length()-1), vars);
                                      else if(vars.containsKey(exp))
                                      return vars.get(exp);
                                      else
                                      return Double.parseDouble(exp);

                                      else
                                      switch(exp.charAt(operatorIndex))
                                      case '+':
                                      return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars);
                                      case '-':
                                      return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars);
                                      case '*':
                                      return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars);
                                      case '/':
                                      return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars);


                                      return 0;





                                      You need to import java.util.Map.



                                      Here is how I use this code:



                                       ExpressionParser p = new ExpressionParser();
                                      Map vars = new HashMap<String, Double>();
                                      vars.put("x", 2.50);
                                      System.out.println(p.eval(" 5 + 6 * x - 1", vars));





                                      share|improve this answer


















                                      • 1





                                        This is a beautiful piece of code. Thank you

                                        – Illishar
                                        Mar 16 '18 at 8:44











                                      • Thank you @Illishar

                                        – user4617883
                                        Mar 16 '18 at 16:01















                                      2














                                      Here is one way to do it. This code is written in Java. Note it does not handle negative numbers right now, but you can add that.



                                      public class ExpressionParser 
                                      public double eval(String exp, Map<String, Double> vars)
                                      int bracketCounter = 0;
                                      int operatorIndex = -1;

                                      for(int i=0; i<exp.length(); i++)
                                      if(operatorIndex < 0)
                                      exp = exp.trim();
                                      if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')')
                                      return eval(exp.substring(1, exp.length()-1), vars);
                                      else if(vars.containsKey(exp))
                                      return vars.get(exp);
                                      else
                                      return Double.parseDouble(exp);

                                      else
                                      switch(exp.charAt(operatorIndex))
                                      case '+':
                                      return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars);
                                      case '-':
                                      return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars);
                                      case '*':
                                      return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars);
                                      case '/':
                                      return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars);


                                      return 0;





                                      You need to import java.util.Map.



                                      Here is how I use this code:



                                       ExpressionParser p = new ExpressionParser();
                                      Map vars = new HashMap<String, Double>();
                                      vars.put("x", 2.50);
                                      System.out.println(p.eval(" 5 + 6 * x - 1", vars));





                                      share|improve this answer


















                                      • 1





                                        This is a beautiful piece of code. Thank you

                                        – Illishar
                                        Mar 16 '18 at 8:44











                                      • Thank you @Illishar

                                        – user4617883
                                        Mar 16 '18 at 16:01













                                      2












                                      2








                                      2







                                      Here is one way to do it. This code is written in Java. Note it does not handle negative numbers right now, but you can add that.



                                      public class ExpressionParser 
                                      public double eval(String exp, Map<String, Double> vars)
                                      int bracketCounter = 0;
                                      int operatorIndex = -1;

                                      for(int i=0; i<exp.length(); i++)
                                      if(operatorIndex < 0)
                                      exp = exp.trim();
                                      if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')')
                                      return eval(exp.substring(1, exp.length()-1), vars);
                                      else if(vars.containsKey(exp))
                                      return vars.get(exp);
                                      else
                                      return Double.parseDouble(exp);

                                      else
                                      switch(exp.charAt(operatorIndex))
                                      case '+':
                                      return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars);
                                      case '-':
                                      return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars);
                                      case '*':
                                      return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars);
                                      case '/':
                                      return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars);


                                      return 0;





                                      You need to import java.util.Map.



                                      Here is how I use this code:



                                       ExpressionParser p = new ExpressionParser();
                                      Map vars = new HashMap<String, Double>();
                                      vars.put("x", 2.50);
                                      System.out.println(p.eval(" 5 + 6 * x - 1", vars));





                                      share|improve this answer













                                      Here is one way to do it. This code is written in Java. Note it does not handle negative numbers right now, but you can add that.



                                      public class ExpressionParser 
                                      public double eval(String exp, Map<String, Double> vars)
                                      int bracketCounter = 0;
                                      int operatorIndex = -1;

                                      for(int i=0; i<exp.length(); i++)
                                      if(operatorIndex < 0)
                                      exp = exp.trim();
                                      if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')')
                                      return eval(exp.substring(1, exp.length()-1), vars);
                                      else if(vars.containsKey(exp))
                                      return vars.get(exp);
                                      else
                                      return Double.parseDouble(exp);

                                      else
                                      switch(exp.charAt(operatorIndex))
                                      case '+':
                                      return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars);
                                      case '-':
                                      return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars);
                                      case '*':
                                      return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars);
                                      case '/':
                                      return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars);


                                      return 0;





                                      You need to import java.util.Map.



                                      Here is how I use this code:



                                       ExpressionParser p = new ExpressionParser();
                                      Map vars = new HashMap<String, Double>();
                                      vars.put("x", 2.50);
                                      System.out.println(p.eval(" 5 + 6 * x - 1", vars));






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Oct 15 '17 at 5:02









                                      user4617883user4617883

                                      374312




                                      374312







                                      • 1





                                        This is a beautiful piece of code. Thank you

                                        – Illishar
                                        Mar 16 '18 at 8:44











                                      • Thank you @Illishar

                                        – user4617883
                                        Mar 16 '18 at 16:01












                                      • 1





                                        This is a beautiful piece of code. Thank you

                                        – Illishar
                                        Mar 16 '18 at 8:44











                                      • Thank you @Illishar

                                        – user4617883
                                        Mar 16 '18 at 16:01







                                      1




                                      1





                                      This is a beautiful piece of code. Thank you

                                      – Illishar
                                      Mar 16 '18 at 8:44





                                      This is a beautiful piece of code. Thank you

                                      – Illishar
                                      Mar 16 '18 at 8:44













                                      Thank you @Illishar

                                      – user4617883
                                      Mar 16 '18 at 16:01





                                      Thank you @Illishar

                                      – user4617883
                                      Mar 16 '18 at 16:01











                                      1














                                      Another option you may want to look into is the Spring.NET Framework's expression evaluation functionality. It can do a lot more than math, too.



                                      However, the entire Spring.NET Framework might be a bit of overkill for your needs if you don't require the rest of the functionality.






                                      share|improve this answer



























                                        1














                                        Another option you may want to look into is the Spring.NET Framework's expression evaluation functionality. It can do a lot more than math, too.



                                        However, the entire Spring.NET Framework might be a bit of overkill for your needs if you don't require the rest of the functionality.






                                        share|improve this answer

























                                          1












                                          1








                                          1







                                          Another option you may want to look into is the Spring.NET Framework's expression evaluation functionality. It can do a lot more than math, too.



                                          However, the entire Spring.NET Framework might be a bit of overkill for your needs if you don't require the rest of the functionality.






                                          share|improve this answer













                                          Another option you may want to look into is the Spring.NET Framework's expression evaluation functionality. It can do a lot more than math, too.



                                          However, the entire Spring.NET Framework might be a bit of overkill for your needs if you don't require the rest of the functionality.







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Oct 19 '10 at 21:31









                                          Joshua RodgersJoshua Rodgers

                                          4,57722529




                                          4,57722529





















                                              1














                                              Related: Equation expression parser with precedence.






                                              share|improve this answer





























                                                1














                                                Related: Equation expression parser with precedence.






                                                share|improve this answer



























                                                  1












                                                  1








                                                  1







                                                  Related: Equation expression parser with precedence.






                                                  share|improve this answer















                                                  Related: Equation expression parser with precedence.







                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited May 23 '17 at 12:18









                                                  Community

                                                  11




                                                  11










                                                  answered Oct 19 '10 at 21:34









                                                  Jared UpdikeJared Updike

                                                  5,17853862




                                                  5,17853862





















                                                      0














                                                      As I answered in this thread (Best Free C# Math Parser using variables, user defined functions, custom operators), you can use Mathos Parser, which you can simply paste into your source code.



                                                       Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser();

                                                      string expr = "(x+(2*x)/(1-x))"; // the expression

                                                      decimal result = 0; // the storage of the result

                                                      parser.LocalVariables.Add("x", 41); // 41 is the value of x

                                                      result = parser.Parse(expr); // parsing

                                                      Console.WriteLine(result); // 38.95





                                                      share|improve this answer

























                                                      • Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.

                                                        – Nic Foster
                                                        Jun 12 '17 at 5:07











                                                      • @NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.

                                                        – Artem
                                                        Jun 12 '17 at 7:39















                                                      0














                                                      As I answered in this thread (Best Free C# Math Parser using variables, user defined functions, custom operators), you can use Mathos Parser, which you can simply paste into your source code.



                                                       Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser();

                                                      string expr = "(x+(2*x)/(1-x))"; // the expression

                                                      decimal result = 0; // the storage of the result

                                                      parser.LocalVariables.Add("x", 41); // 41 is the value of x

                                                      result = parser.Parse(expr); // parsing

                                                      Console.WriteLine(result); // 38.95





                                                      share|improve this answer

























                                                      • Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.

                                                        – Nic Foster
                                                        Jun 12 '17 at 5:07











                                                      • @NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.

                                                        – Artem
                                                        Jun 12 '17 at 7:39













                                                      0












                                                      0








                                                      0







                                                      As I answered in this thread (Best Free C# Math Parser using variables, user defined functions, custom operators), you can use Mathos Parser, which you can simply paste into your source code.



                                                       Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser();

                                                      string expr = "(x+(2*x)/(1-x))"; // the expression

                                                      decimal result = 0; // the storage of the result

                                                      parser.LocalVariables.Add("x", 41); // 41 is the value of x

                                                      result = parser.Parse(expr); // parsing

                                                      Console.WriteLine(result); // 38.95





                                                      share|improve this answer















                                                      As I answered in this thread (Best Free C# Math Parser using variables, user defined functions, custom operators), you can use Mathos Parser, which you can simply paste into your source code.



                                                       Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser();

                                                      string expr = "(x+(2*x)/(1-x))"; // the expression

                                                      decimal result = 0; // the storage of the result

                                                      parser.LocalVariables.Add("x", 41); // 41 is the value of x

                                                      result = parser.Parse(expr); // parsing

                                                      Console.WriteLine(result); // 38.95






                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited May 23 '17 at 12:18









                                                      Community

                                                      11




                                                      11










                                                      answered Apr 30 '13 at 14:58









                                                      ArtemArtem

                                                      494921




                                                      494921












                                                      • Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.

                                                        – Nic Foster
                                                        Jun 12 '17 at 5:07











                                                      • @NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.

                                                        – Artem
                                                        Jun 12 '17 at 7:39

















                                                      • Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.

                                                        – Nic Foster
                                                        Jun 12 '17 at 5:07











                                                      • @NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.

                                                        – Artem
                                                        Jun 12 '17 at 7:39
















                                                      Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.

                                                      – Nic Foster
                                                      Jun 12 '17 at 5:07





                                                      Unfortunately this project is hosted at Codeplex, which is closing. I can't manage to even get a look at the source at Codeplex right now. It would be nice if the project could be rehosted on Github or Bitbucket or the like.

                                                      – Nic Foster
                                                      Jun 12 '17 at 5:07













                                                      @NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.

                                                      – Artem
                                                      Jun 12 '17 at 7:39





                                                      @NicFoster, please take a look at github.com/MathosProject/Mathos-Parser. There are also other versions of it at github.com/MathosProject.

                                                      – Artem
                                                      Jun 12 '17 at 7:39











                                                      0














                                                      I recomend you to use MEEL for this.



                                                      // parse string to IExpression (symbolic type)
                                                      IExpression expression = BaseExpression.Parse("(x+(2*x)/(1-x))");

                                                      // create your own collection for attributes
                                                      var attributes = new MathAttributeCollection();
                                                      // create local variable named "x" with value 5
                                                      var attributeX = new ScalarAttrInt("x") Value = new ScalarConstInt(5);
                                                      attributes.Add(attributeX);

                                                      // execute math expression where x=5
                                                      var result = expression.Execute(attributes);

                                                      MessageBox.Show(result.GetText());
                                                      // result: 2.5





                                                      share|improve this answer



























                                                        0














                                                        I recomend you to use MEEL for this.



                                                        // parse string to IExpression (symbolic type)
                                                        IExpression expression = BaseExpression.Parse("(x+(2*x)/(1-x))");

                                                        // create your own collection for attributes
                                                        var attributes = new MathAttributeCollection();
                                                        // create local variable named "x" with value 5
                                                        var attributeX = new ScalarAttrInt("x") Value = new ScalarConstInt(5);
                                                        attributes.Add(attributeX);

                                                        // execute math expression where x=5
                                                        var result = expression.Execute(attributes);

                                                        MessageBox.Show(result.GetText());
                                                        // result: 2.5





                                                        share|improve this answer

























                                                          0












                                                          0








                                                          0







                                                          I recomend you to use MEEL for this.



                                                          // parse string to IExpression (symbolic type)
                                                          IExpression expression = BaseExpression.Parse("(x+(2*x)/(1-x))");

                                                          // create your own collection for attributes
                                                          var attributes = new MathAttributeCollection();
                                                          // create local variable named "x" with value 5
                                                          var attributeX = new ScalarAttrInt("x") Value = new ScalarConstInt(5);
                                                          attributes.Add(attributeX);

                                                          // execute math expression where x=5
                                                          var result = expression.Execute(attributes);

                                                          MessageBox.Show(result.GetText());
                                                          // result: 2.5





                                                          share|improve this answer













                                                          I recomend you to use MEEL for this.



                                                          // parse string to IExpression (symbolic type)
                                                          IExpression expression = BaseExpression.Parse("(x+(2*x)/(1-x))");

                                                          // create your own collection for attributes
                                                          var attributes = new MathAttributeCollection();
                                                          // create local variable named "x" with value 5
                                                          var attributeX = new ScalarAttrInt("x") Value = new ScalarConstInt(5);
                                                          attributes.Add(attributeX);

                                                          // execute math expression where x=5
                                                          var result = expression.Execute(attributes);

                                                          MessageBox.Show(result.GetText());
                                                          // result: 2.5






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Feb 6 '15 at 10:26









                                                          supertohasupertoha

                                                          1377




                                                          1377



























                                                              draft saved

                                                              draft discarded
















































                                                              Thanks for contributing an answer to Stack Overflow!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid


                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.

                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function ()
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3972854%2fparse-math-expression%23new-answer', 'question_page');

                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                              Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                                              Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript