An arithmetic expression evaluator built using .NET
- Integers, decimal numbers
420
,1.23
- Addition, Subtraction, Multiplication, Division, Exponentiation
+
,-
,*
,/
,^
- Negative numbers
-(2)
,-2
- Parenthesized expressions
2*(1+3)
- Implicit multiplication
-2(3+1)
- Extendability
Parser
implemented as a recursive descent parser
-
Calculate the result on an expression:
using EvalExpression.Extensions; using @eval = EvalExpression.EvalExpression; var expression = "-(1-(2.5+3*2)^(4/2))"; var result = @eval .Build(expression) // builds the AST .Evaluate(); // evaluates the AST // Will output: Expression '-(1-(2.5+3*2)^(4/2))' resolves to: 71.25 Console.WriteLine($"Expression '{expression}' resolves to: {result}");
-
Convert the AST to JSON:
using EvalExpression.Extensions; using @eval = EvalExpression.EvalExpression; var result = @eval .Build("-(1-(2.5+3*2)^(4/2))") .ToJsonString(); // serializes to JSON
- .NET 8 SDK
- Visual Studio or other IDE
- Clone this repo
git clone https://github.com/dariomrk/eval-expression.git
- The source (
/src
) is comprised of four projects:Lexer
: converts the string expression into tokensParser
: builds an abstract syntax treeInterpreter
: evaluates the treeEvalExpression
: provides an easy to use API
- The code is tested with unit & integration tests (
/test
)- Run them with
dotnet test
or using the integrated test explorer of your IDE
- Run them with