Coder Social home page Coder Social logo

dangl.calculator's Introduction

Dangl.Calculator

Build Status NuGet MyGet

Online Documentation
Changelog

This calculator is using the ANTLR4 C# target to calculate results from formulas that are passed in as string.

Whenever a calculation is performed, a CalculationResult is returned with the following properties:

Property Type
IsValid bool true if the formula could be parsed and calculated, else false
ErrorPosition int Position of the offending symbol in the line, 0 based index, for invalid results, else null
ErrorMessage string ANTLR error message for invalid formulas, else null
Result double NaN for invalid formulas, else the actual result

You can find the TypeScript version here: https://github.com/GeorgDangl/antlr-calculator

Installation

Install it via NuGet: Dangl.Calculator

CI builds are available via MyGet.

https://www.myget.org/F/dangl/api/v3/index.json

Compatibility

This project targets netstandard2.0, netstandard1.1, net45 and net40. Due to .Net 4.5.2 being the currently latest supported version by Microsoft and the xUnit test suite, no tests are run for net45 and net451.
The .NET 4.0 target is for compatibility reasons, it is not tested and requires .NET compilers for version 4.5 or newer to properly function.

Project Configuration

If this project is consumed in a project using the full .Net framework with a newer version of Antlr4.Runtime, the necessary AssemblyBindingRedirects are not automatically generated with the current dotnet CLI tooling. This is scheduled to be fixed with the 2.0 release. In the meantime, the following should be added to the consumers csproj:

<PropertyGroup Condition=" '$(TargetFramework)' == 'net461' ">
  <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>

The Condition=" '$(TargetFramework)' == 'net461' " attribute may be changed as necessary or removed.

Example

using Dangl.Calculator;

public void Example()
{
    var formula = "5+5";
    var calculation = Calculator.Calculate(formula);

    Console.WriteLine(calculation.Result);
    Console.WriteLine(calculation.IsValid);

    // 10.0
    // true
}

Supported functions

Expression
FLOOR expression Round down to zero accuracy
CEIL expression Round up to zero accuracy
ABS expression Absolute value
ROUNDK '(' expression ';' expression ')' Round expr_1 with expr_2 accuracy
ROUND expression Round with zero accuracy
TRUNC expression Trim decimal digits
SIN expression Sinus
COS expression Cosinus
TAN expression Tangens
COT expression Cotangens
SINH expression Sinus Hypererbolicus
COSH expression Cosinus Hyperbolicus
TANH expression Tangens Hyperbolicus
ARCSIN expression Inverse Sinus
ARCCOS expression Inverse Cosinus
ARCTAN expression Inverse Tangens
ARCTAN2 '(' expression ';' expression ')' Atan2
ARCCOT expression Inverse Cotangens
EXP expression e ^ expr
LN expression Logarithm to e
EEX expression 10 ^ expr
LOG expression Logarithm to 10
RAD expression Angle to radians (360° base)
DEG expression Radians to angle (360° base)
SQRT expression Square root
SQR expression Square product
expression op = ('^'|'**') expression expr_1 to the expr_2 th power
expression (MOD | '%' ) expression Modulo
expression DIV expression Whole part of division rest
expression op = ('~'|'//') expression expr_1 nth root of expr_2
expression op = ('*'|'/') expression Multiplication or division
expression op = ('+'|'-') expression Addition or subtraction
NUMBER Single integer or float number
MIN '(' expression (';' expression)* ')' Minimum
MAX '(' expression (';' expression)* ')' Maximum
NUMBER Single integer or float number
'(' expression ')' Expression within parentheses
PI '()'? Mathematical constant pi = 3,141593
expression E+ expression Exponent, e.g. 10e+43
expression E- expression Inverted Exponent, e.g. 10e-43
EULER Mathematical constant e = 2,718282
'-' expression Unary minus sign (negative numbers)
'+' expression Unary plus sign (positive numbers)
'(' expression ')' expression Expressions without multiplication sign, e.g. 2(3) -> 2*(3)
expression '(' expression ')' Expressions without multiplication sign, e.g. 2(3) -> 2*(3)

expression may be any expression as functions can be nested. Example: DEG(2*PI) or LOG(10^3).

Formulas can be case invariant, e.g. SIN, sin and siN are all considered the same.

An optional equals sign = at the end of the function is allowed.

Comments in Formulas

Comments in Formulas are supported by encapsulating them either in /*...*/, '...' or "..." quote styles. Examples:

4/*Length*/*3/*Width*/ resolves to 12

4'Length'*3'Width' resolves to 12

4"Length"*3"Width" resolves to 12

Substitutions

The calculator can be called with an overload that accepts a callback function for substitution values. For example, take the following formula:
1,2*#Z4+3
Here, #Z4 is a substitution, which is a placeholder that can be externally supplied. Let's say you want to resolve #Z4 to the value three, you could make this simple call:

var formula = "1,2*#Z4+3";
var result = Calculator.Calculate(formula, substitution =>
{
    if (substitution == "#Z4")
    {
        return 3;
    }

    return null;
});

The callback is in the form of a Func<string, double?>, and it will be called for every substitution found in the formula. Multiple substitutions are supported. If duplicates in substitutions are present, the calculator will request each one individually. If a substitution resolves to null, the formula is considered invalid.

Substitutions must always start with the # character and can then have the following characters: [a-z] | [A-Z] | [äÄöÖüÜ] | [0-9]

Ranges

Similar to Substitutions, the calculator also can handle Ranges. They look like two substitutions joined by two points, e.g. #1..#5. A separate range resolver can be supplied to the calculator as a callback function, so that you can plug in your own logic to resolve ranges when being given a Start and End substitution.

Trailing comments

Formulas may be terminated with a semicolon ; at the end, followed by extra input that is not evaluated. This is useful when, instead of regular comments, you just want to attach some trailing formation at the end of a formula. For example, the following formula:
1 + 3; As per our counting
Would just evaluate the 1 + 3 portion and return a valid result with the value 4, ignoring the trailing semicolon and all input that follows.

Assembly Strong Naming & Usage in Signed Applications

This module produces strong named assemblies when compiled. When consumers of this package require strongly named assemblies, for example when they themselves are signed, the outputs should work as-is. The key file to create the strong name is adjacent to the csproj file in the root of the source project. Please note that this does not increase security or provide tamper-proof binaries, as the key is available in the source code per Microsoft guidelines


MIT Licence

dangl.calculator's People

Contributors

georgdangl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

dangl.calculator's Issues

.NET 5

Hey,
Any plan to update this to .NET 5?

Can't use Dangl.Calculator

Hi. I'm trying to make a simple calculator app. I used Visual Studio's NuGet to install Dangl.Calculator. After I installed it, I wrote using Dangl.Calculator but it's greyed out (not available). I can see Dangl.Calculator on the References category on the Solution Explorer but it still doesn't work. When using the code to calculate I get this error:

CS0234 The type or namespace name 'Calculate' does not exist in the namespace 'Calculator' (are you missing an assembly reference?

I'm an amateur programmer, can you help me fix this thing? My project is targeting NET Framework 4.8

How do you compile the code

I am struggling how to compile the Lexer and the parser, I took your example and download it and compile it. That works. If I go under the obj folder and take any of the frameworks folders and get the generated files and replace the existing ones, they don't compile.
If I am planning to start only from the .g4 file which are the steps you recommend to compile the generated code?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.