Skip to content

An arithmetic expression evaluator built using .NET

License

Notifications You must be signed in to change notification settings

dariomrk/EvalExpression

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

EvalExpression

Top language Build & test workflow GitHub issues GitHub pull requests GitHub

An arithmetic expression evaluator built using .NET

Supports:

  • 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

Usage sample:

  • 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

Prerequisites:

Getting started:

  • 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 tokens
    • Parser: builds an abstract syntax tree
    • Interpreter: evaluates the tree
    • EvalExpression: 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