An open API service indexing awesome lists of open source software.

https://github.com/matheval/expression-evaluator-c-sharp

Matheval is a mathematical expressions evaluator library written in C#. Allows to evaluate mathematical, boolean, string and datetime expressions
https://github.com/matheval/expression-evaluator-c-sharp

calculator eval evaluator expression-evaluator expresssion fomular math mathematical-expressions-evaluator mathematics

Last synced: about 2 months ago
JSON representation

Matheval is a mathematical expressions evaluator library written in C#. Allows to evaluate mathematical, boolean, string and datetime expressions

Awesome Lists containing this project

README

          

# About MathEval
[![NuGet version (org.matheval)](https://img.shields.io/nuget/v/org.matheval.svg?style=flat-square)](https://www.nuget.org/packages/org.matheval/)

Matheval is a mathematical expressions evaluator library written in C#. Allows to evaluate mathematical, boolean, string and datetime expressions

Code is written in pure C#, run on the fly. We don't use any third party libraries or packages

If you get any bugs please let me know by creating a new issue.

**Many thanks to our contributors:**

[Thanhrin](https://github.com/ThanhRin) (from Da Nang, VietNam)

[Eduardo Salinas](https://github.com/butulia) (from Huesca, Spain)

# Installation

Using Package Manager

```bash
PM> Install-Package org.matheval -Version 1.0.0.3
```

# Supported operators, contants, functions

## Supported Operators

Operator

Description

+

Additive operator / Unary plus / Concatenate string / Datetime addition

&

Concatenate string

Subtraction operator / Unary minus / Datetime subtraction

*

Multiplication operator, can be omitted in front of an open bracket

/

Division operator

%

Remainder operator (Modulo)

^

Power operator

## Supported conditional statements

Conditional statement

Description

IF(logical_condition, value_if_true, value_if_false)

Example:
`IF(2>1,"Pass","Fail")`

SWITCH(expression, val1,result1, [val2,result2], …, [default])

Example:
`SWITCH(3+2,5,"Apple",7,"Mango",3,"Good","N/A")`

## Supported logical and math functions

Function*

Description

AND(logical1, [logical2], …)

Determine if all conditions are TRUE

OR(logical1, [logical2], …)

Determine if any conditions in a test are TRUE

NOT(_logical_)

To confirm one value is not equal to another

XOR(logical1, [logical2], …)

Exclusive OR function

SUM(number1, [number2],…)

Return sum of numbers supplied

AVERAGE(number1, [number2],…)

Return average of numbers supplied

MIN(number1, [number2],…)

Return the smallest value from the numbers supplied

MAX(number1, [number2],…)

Return the biggest value from the numbers supplied

MOD(number, divisor)

Get remainder of two given numbers after division operator.

ROUND(number, num_digits)

Returns the rounded approximation of given number using half-even rounding mode
( you can change to another rounding mode)

FLOOR(number, significance)

Rounds a given number towards zero to the nearest multiple of a specified significance

`CEILING`(number, significance)

Rounds a given number away from zero, to the nearest multiple of a given number

POWER(number, power)

Returns the result of a number raised to a given power

RAND()

Produces a random number between 0 and 1

SIN(number)

Returns the trigonometric sine of the angle given in radians

SINH(number)

Returns the hyperbolic sine of a number

ASIN(number)

Returns the arc sine of an angle, in the range of -pi/2 through pi/2

COS(number)

Returns the trigonometric cos of the angle given in radians

COSH(number)

Returns the hyperbolic cos of a number

ACOS(number)

Returns the arc cosine of an angle, in the range of 0.0 through pi

TAN(number)

Returns the tangent of the angle given in radians

TANH(number)

Returns the hyperbolic tangent of a number

ATAN(number)

Returns the arc tangent of an angle given in radians

ATAN2(x_number, y_number)

Returns the arctangent from x- and y-coordinates

COT(number)

Returns the cotangent of an angle given in radians.

COTH(number)

Returns the hyperbolic cotangent of a number

SQRT(number)

Returns the correctly rounded positive square root of given number

LN(number)

Returns the natural logarithm (base _e_) of given number

LOG10(number)

Returns the logarithm (base 10) of given number

EXP(number)

Returns e raised to the power of given number

ABS(number)

Returns the absolute value of given number

FACT(number)

Returns the factorial of a given number

SEC(number)

Returns the secant of an angle given in radians

CSC(number)

Returns the cosecant of an angle given in radians

PI()

Return value of Pi

RADIANS(degrees)

Convert degrees to radians

DEGREES(radians)

Convert radians to degrees

INT(number)

Returns the Integer value of given number

## Supported Constants

Constant

Description

e

The value of _e_

PI

The value of _PI_

TRUE

The boolean true value

FALSE

The boolean false value

NULL

The null value

## Supported text functions

Function

Description

LEFT(text, num_chars)

Extracts a given number of characters from the left side of a supplied text string

RIGHT(text, num_chars)

Extracts a given number of characters from the right side of a supplied text string

MID(text, start_num, num_chars)

Extracts a given number of characters from the middle of a supplied text string

REVERSE(text)

Reverse a string

ISNUMBER(text)

Check if a value is a number

LOWER(text)

Converts all letters in the specified string to lowercase

UPPER(text)

Converts all letters in the specified string to uppercase

PROPER(text)

Capitalizes words given text string

TRIM(text)

Removes extra spaces from text

LEN(text)

Returns the length of a string/ text

TEXT(value, [format_text])

Convert a numeric value into a text string. You can use the TEXT function to embed formatted numbers inside text
Example:
`

TEXT(123) -> 123

`TEXT(123) -> 123`

TEXT(DATEVALUE("2021-01-23"),"dd-MM-yyyy") -> 23-01-2021

`TEXT(DATEVALUE("2021-01-23"),"dd-MM-yyyy") -> 23-01-2021`

TEXT(2.61,"hh:mm") -> 14:38

`TEXT(2.61,"hh:mm") -> 14:38`

TEXT(2.61,"[hh]") -> 62

`TEXT(2.61,"[hh]") -> 62`

TEXT(2.61,"hh-mm-ss") -> 14-38-24

`TEXT(2.61,"hh-mm-ss") -> 14-38-24`

TEXT(DATEVALUE("2021-01-03")-DATEVALUE("2021-01-01"),"[h]") -> 48

`TEXT(DATEVALUE("2021-01-03")-DATEVALUE("2021-01-01"),"[h]") -> 48`

TEXT(TIME(12,00,00)-TIME(10,30,10),"hh hours and mm minutes and ss seconds") -> "01 hours and 29 minutes and 50 seconds"

`TEXT(TIME(12,00,00)-TIME(10,30,10),"hh hours and mm minutes and ss seconds") -> "01 hours and 29 minutes and 50 seconds"``

REPLACE(old_text, start_num, num_chars, new_text)

Replaces characters specified by location in a given text string with another text string

SUBSTITUTE(text, old_text, new_text)

Replaces a set of characters with another

FIND(find_text, within_text, [start_num])

Returns the location of a substring in a string (case sensitive)

SEARCH(find_text, within_text, [start_num])

Returns the location of a substring in a string (case insensitive)

CONCAT(text1, text2, text3,…)

Combines the text from multiple strings

ISBLANK(text)

Returns TRUE when a given string is null or empty, otherwise return FALSE

REPT(text, repeat_time)

Repeats characters a given number of times

CHAR(char_code)

Return character from ascii code

CODE(char)

Returns a ascii code of a character

VALUE(text)

Convert numbers stored as text to numbers

# Usage examples

## Basic evaluator
```cs
using System;
using org.matheval;

public class Program
{
public static void Main()
{
Expression expression = new Expression("(a + b) / 2 ");
expression.Bind("a", 3);
expression.Bind("b",5);
Object value = expression.Eval();
Console.WriteLine("Result: "+value); //Result: 4

}
}
```

## Conditional statements
IF/ELSE
```cs
using System;
using org.matheval;

public class Program
{
public static void Main()
{
Expression expression = new Expression("IF(time>8, (HOUR_SALARY*8) + (HOUR_SALARY*1.25*(time-8)), HOUR_SALARY*time)");
//bind variable
expression.Bind("HOUR_SALARY", 10);
expression.Bind("time", 9);
//eval
Decimal salary = expression.Eval();
Console.WriteLine(salary); //return 92.5
}
}
```
SWITCH/CASE
```cs
Expression expr = new Expression("SWITCH(name,1,'apple',2,'mango',3,'banana','N/A')");
//Bind variable
expr.Bind("name", 2);
//eval
String value = expr.Eval(); //return "mango"
```

## Validate expression
```cs
Expression expression = new Expression("SUM(1,2,3) + true");
List errors = expression.GetError();
if(errors.Count > 0)
{
foreach(String error in errors)
{
Console.WriteLine(error);
}
}
```

## Get variables that appear in the expression
```cs
Expression expression = new Expression("sin(pi/2+x)-cos(x) = a");
//validate expression
List errors = expression.GetError();
if (errors.Count == 0)
{
// get variables
List variables = expression.getVariables();
foreach (String variable in variables)
{
Console.WriteLine(variable); // will print x, a
}
}
```
## Disable functions
```cs
Expression expression = new Expression();
expression.DisableFunction("SIN");
expression.DisableFunction("COS");
```
```cs
Expression expression = new Expression();
expression.DisableFunction(new string[] { "SIN", "COS" });
```
# Work with number expression
Scale and rounding mode

Use setScale() method to set number of digits to the right of the decimal point. Use setRoundingMode() method to set rounding mode. You can choose 1 of the following options:

MidpointRounding.AwayFromZero
MidpointRounding.ToEven
MidpointRounding.ToZero
```cs
Expression expression = new Expression("pi/2");
expression.SetScale(3);
expression.SetRoundingMode(MidpointRounding.ToEven);
Decimal value = expression.Eval();//return 1.571
```

## Min, max, sum, avg

```cs
Expression expr = new Expression("MIN(a,b,c)");
expr.Bind("a", 2);
expr.Bind("b", 3);
expr.Bind("c", 16);
int value = expr.Eval(); // return 2
```

```cs
Expression expr = new Expression("MAX(a)");
expr.Bind("a", new List { 10m, 9.6m, 135, 724.2m, 6m, -4m });
Decimal value = expr.Eval(); // return 724.2
```

```cs
Expression expr = new Expression("SUM(a,b,c)");
expr.Bind("a", 2d);
expr.Bind("b", 3d);
expr.Bind("c", 16d);
Double sum = expr.Eval(); // return 21
expr.SetFomular("AVERAGE(a,b,c)");
Double avg = expr.Eval(); // return 7
```

```cs
Expression expr = new Expression("SUM(a)");
expr.Bind("a", new List { 2m, 3m, 16m });
Decimal sum = expr.Eval(); // return 21
expr.SetFomular("AVERAGE(a)");
Decimal avg = expr.Eval(); // return 7
```

```cs
using System;
using org.matheval;

public class Program
{
public static void Main()
{
Expression expr = new Expression("MIN(2,3,16)");
int min = expr.Eval();
Console.WriteLine(min);// return 2 (min)

expr.SetFomular("Max(2,3,16)");
int max = expr.Eval();
Console.WriteLine(max);// return 16 (max)

expr.SetFomular("Sum(2,3,16)");
decimal sum = expr.Eval();
Console.WriteLine(sum);// return 21 (sum)

expr.SetFomular("average(2,3,16)");
decimal average = expr.Eval();
Console.WriteLine(average);// return 7 (average)
}
}
```
## Round, floor, ceiling
```cs
using System;
using org.matheval;

public class Program
{
public static void Main()
{
Expression expr = new Expression("ROUND(2.149, 1)");
Object value = expr.Eval();
Console.WriteLine("ROUND(2.149, 1) = "+value); //return 2.1

expr = new Expression("FLOOR(2.149)");
value = expr.Eval();
Console.WriteLine("FLOOR(2.149) = "+value); //return 2

expr = new Expression("FLOOR(3.7,2)");
value = expr.Eval();
Console.WriteLine("FLOOR(3.7,2) = "+value); //return 2

expr = new Expression("CEILING(2.149)");
value = expr.Eval();
Console.WriteLine("CEILING(2.149) = "+value); //return 3

expr = new Expression("CEILING(1.5, 0.1)");
value = expr.Eval();
Console.WriteLine("CEILING(1.5, 0.1) = "+value); //return 1.5
}
}
```
## Trigonometry
```cs
Expression expr = new Expression('SIN(PI())^2+COS(PI())^2');
Object value = expr.Eval(); //return 1
```

```cs
Expression expr = new Expression("sin(a) - cos(a) = SQRT(2) * sin(a - pi / 4)");
bool value = expr.Bind("a", Math.PI/5).Eval(); //return true
```

```cs
using System;
using org.matheval;

public class Program
{
public static void Main()
{
Expression expr = new Expression("tan(a)^3-((3*sin(a)-sin(3*a))/(3*cos(a)+cos(3*a)))");
Decimal value = expr.Bind("a", Math.PI/6).Eval();
Console.WriteLine(value); //return 0
}
}
```
## Unary operator
```cs
Expression expr = new Expression("3--2+--3-(-(++2))");
Object value = expr.Eval(); //return 10
```

## Deal with string
```cs
using System;
using org.matheval;

public class Program
{
public static void Main()
{
Expression taxExpr = new Expression("IF(LOWER(TAX_CODE)='vat',amount*10/100,IF(LOWER(TAX_CODE)='gst',amount*15/100,0))");
taxExpr.Bind("TAX_CODE","GST");
taxExpr.Bind("amount", 5005m);
Decimal value = taxExpr.Eval();
Console.WriteLine(value);
}
}
```

## Left, right
```cs
Expression expr = new Expression("IF(VALUE(LEFT(date,4))<2020,'n/a','generation of ' & LEFT(date,4))");
expr.Bind("date", "2022-01-20");
String value = expr.Eval();
```

## Calculate tax
```cs
Expression taxExpr = new Expression("IF(LOWER(TAX_CODE)='vat',amount*10/100,IF(LOWER(TAX_CODE)='gst',amount*15/100,0))");
taxExpr.Bind("TAX_CODE","GST");
taxExpr.Bind("amount", 5005m);
Decimal value = taxExpr.Eval();
```

## Concatenate strings
```cs
using System;
using org.matheval;

public class Program
{
public static void Main()
{
Expression expr = new Expression("CONCAT('The United States of ', 'America')");
String value = expr.Eval();
Console.WriteLine(value);//The United States of America
}
}
```

## Datetime
December 30, 1899 date system

We use 1899 date system, the first day that is supported is December 30, 1899. Any date you supply to this library will be converted into a serial number that represents the number of elapsed days starting from December 30, 1899. Look at the sample below:
```cs
Expression expr = new Expression("DATETIME(2025,01,02,12,11,10)");
Decimal serialDate = expr.Eval(); // return 45659.507755 (days elapsed from December 30, 1899)
DateTime datetime = expr.Eval(); // return 2025/01/02 12:11:10
```
## Setting holidays and weekend for expression context
```cs
Expression expr = new Expression("NETWORKDAYS(B5,C5)");
expr.SetHolidays(
new DateTime[] {
new DateTime(2017,11,23),
new DateTime(2017, 12, 25),
new DateTime(2018, 1, 1)
}
);
expr.SetWeekends(new Int32[] { 1, 2, 3 }); //Sunday = 0, ..., Saturday = 6
expr.Bind("B5", new DateTime(2017, 1, 15));
expr.Bind("C5", new DateTime(2018, 1, 21));
Decimal value = expr.Eval(); //return 212
```
## Calculate networkday
```cs
Expression expr = new Expression("NETWORKDAYS(DATEVALUE('2021-03-30'),DATEVALUE('2022-05-16'))");
int value = expr.Eval(); // return 295
```
```cs
Expression expr = new Expression("NETWORKDAYS(startdate,enddate)");
expr.Bind("startdate", new DateTime(2021, 08, 11));
expr.Bind("enddate", new DateTime(2021, 10, 4));
Object value = expr.Eval(); // return 39
```
## Calculates the number of days, months, or years between two dates.
```cs
Expression expr = new Expression("DATEDIF(DATEVALUE('2021-01-31'),DATEVALUE('2029-08-29'),'Y')");
Object value = expr.Eval(); // return 8
```
```cs
Expression expr = new Expression("DATEDIF(DATEVALUE('2021-01-31'),DATEVALUE('2029-08-29'),'M')");
Object value = expr.Eval(); // return 102
```
```cs
Expression expr = new Expression("DATEDIF(DATEVALUE('2021-01-31'),DATEVALUE('2029-08-29'),'D')");
Object value = expr.Eval(); // return 3132
```
```cs
Expression expr = new Expression("DATEDIF(DATEVALUE('2021-01-31'),DATEVALUE('2029-08-29'),'MD')");
Object value = expr.Eval(); // return 29
```
## Calculates the number of days, hours, mins between two datetime.
```cs
Expression expr = new Expression("DATETIME(2021,2,28,15,50,0)-DATETIME(2021,2,21,23,0,0)");
Decimal value = expr.Eval(); // return 6.70139 (days)
```
```cs
Expression expr = new Expression("(DATETIME(2021,2,28,15,50,0)-DATETIME(2021,2,21,23,0,0))*24");
Decimal value = expr.Eval(); // return 160.8 (hours)
```
```cs
Expression expr = new Expression("(DATETIME(2021,2,28,15,50,0)-DATETIME(2021,2,21,23,0,0))*24*60");
Decimal value = expr.Eval(); // return 9650 (mins)
```
## Calculates the number of days, hours, mins between two timespan.
```cs
Expression expr = new Expression("DATETIME(2021,2,28,15,50,0)-DATETIME(2021,2,21,23,0,0)");
Object value = expr.Eval(); // return 6.701389 (days)
```
## Substract, add datetime
```cs
Expression expr = new Expression("DATETIME(2021,2,28,15,50,0)-DATETIME(2021,2,21,23,0,0)");
Object value = expr.Eval(); // return 6.701389 (days)
```
```cs
Expression expr = new Expression("DATE(2021,2,28)-DATE(2021,2,21)");
Object value = expr.Eval(); // return 7 (days)
```
```cs
Expression expr = new Expression("DATE(2021,9,20)+3");
DateTime value = expr.Eval(); // return 2021-09-23
```
```cs
Expression expr = new Expression("TIME(10,10,0)+TIME(10,10,0)");
TimeSpan value = expr.Eval(); // return 20:20:00
```

## License
MIT license