Click here to Skip to main content
11,490,408 members (35,442 online)
Click here to Skip to main content

Math Parser .NET C#

, 28 Feb 2014 GPL3 51.1K 5.2K 59
Rate this:
Please Sign up or sign in to vote.
This is light, fast and simple to understand mathematical parser designed in one class, which receives as input a mathematical expression (System.String) and returns the output value (System.Double)


This is light, fast and simple to understand mathematical parser designed in one class, which receives as input a mathematical expression (System.String) and returns the output value (System.Double). For example, if your input string is "√(625)+25*(3/3)" then parser returns double value — 50. 


The idea was to create a string calculator for educational goals.  

How it work   


For more please look at the code, I tried to explain the work of the parser in the comments and how it can be changed and extended.  

Convert to RPN:

* Input operators are replaced by the corresponding token (its necessary to distinguish unary from binary). 

Using the code  


    public static void Main()
            MathParser parser = new MathParser();
	    string s1 = "pi+5*5+5*3-5*5-5*3+1E1";
	    string s2 = "sin(cos(tg(sh(ch(th(100))))))";
            bool isRadians = false;
            double d1 = parser.Parse(s1, isRadians);
	    double d2 = parser.Parse(s2, isRadians);

            Console.WriteLine(d1); // 13.141592...
	    Console.WriteLine(d2); // 0.0174524023974442


Ariphmetical operators :

  • () — parentheses;  
  • + —  plus (a + b); 
  • - — minus (a - b); 
  • * — multiplycation symbol (a * b); 
  • / — divide symbol (a / b); 
  • ^ — degree symbol (a ^ b).  

Functions :    

Trigonometric functions: 

  • sin(x);
  • cos(x);
  • tg(x);  
  • ctg(x). 

Hyperbolic functions:

  • sh(x);
  • ch(x);
  • th(x).  

Other functions: 
  • √(a), sqrt(a) — square root of a number; 
  • exp(x)  — exponential function (or just use e^x);  
  • (a)log(b) — logarithm; 
  • ln(x) — natural logarithm; 
  • abs(x) — absolute value.  


  • pi — 3.14159265...;  
  • e — 2.71828183....  

Arguments of the trigonometric functions can be expressed as radians (true) or degrees (false) by sending appropriate bool value to parse method. Example (as radians):   

parser.Parse("sin(90)", true);

Work with any char decimal separator in real number (regional settings).

New operators, functions and constants can be easily added to the code. 

This parser is simple (special designed in single class), convenient for the further implementation, expansion and modification.      

Points of Interest     

I better understand how parsers work and learned about the reverse-polish notation.


  • 2012/05/09: released the source code (1_0); 
  • 2012/06/07: optimized parser (1_2);    
  • 2014/02/28: rewritten version (1_4). 


This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


About the Author


Kazakstan Kazakstan
My full name is Yerzhan Kalzhani. I’m a pragmatic software developer who loves tasks that are interesting and challenging. My motto in software developing: "Quality, Performance and Agile".

I prefer systematic approach when solving problem, so I think that every good developer first of all should be able to manage the complexity of a software system and produce the well-structured solution for a poor defined problem.

Comments and Discussions

QuestionMulti-argument functions Pin
lianaent15-Mar-15 6:04
memberlianaent15-Mar-15 6:04 
AnswerRe: Multi-argument functions Pin
lianaent15-Mar-15 9:29
memberlianaent15-Mar-15 9:29 
GeneralRe: Multi-argument functions Pin
lianaent15-Mar-15 12:04
memberlianaent15-Mar-15 12:04 
QuestionConditional Expressions possible? Pin
mbs-systems14-Feb-15 13:54
membermbs-systems14-Feb-15 13:54 
BugTests with Log function seem wrong Pin
DEGT5-Feb-15 11:00
memberDEGT5-Feb-15 11:00 
NewsNow supporting Complex Numbers [modified] Pin
DEGT2-Feb-15 9:39
memberDEGT2-Feb-15 9:39 
QuestionSymbol transformation Pin
DEGT29-Jan-15 9:31
memberDEGT29-Jan-15 9:31 
QuestionExcellent job Pin
jigoch19-Dec-14 6:28
memberjigoch19-Dec-14 6:28 
GeneralGreat Job! Pin
miro125-Mar-14 4:03
membermiro125-Mar-14 4:03 
GeneralRe: Great Job! Pin
kirnbas24-Mar-14 6:35
memberkirnbas24-Mar-14 6:35 
GeneralMy vote of 4 Pin
Florian Rappl29-Aug-12 9:50
memberFlorian Rappl29-Aug-12 9:50 
GeneralRe: My vote of 4 Pin
kirnbas29-Aug-12 20:34
memberkirnbas29-Aug-12 20:34 
GeneralRe: My vote of 4 Pin
Florian Rappl29-Aug-12 22:27
memberFlorian Rappl29-Aug-12 22:27 
GeneralRe: My vote of 4 Pin
Andreas Gieriet27-Jan-13 9:19
memberAndreas Gieriet27-Jan-13 9:19 
AnswerCode Pin
Clifford Nelson24-Aug-12 8:07
memberClifford Nelson24-Aug-12 8:07 
GeneralRe: Code Pin
kirnbas24-Aug-12 8:46
memberkirnbas24-Aug-12 8:46 
NewsSym Pin
Warren Harding16-Aug-12 21:32
memberWarren Harding16-Aug-12 21:32 
GeneralRe: Sym Pin
kirnbas24-Aug-12 7:19
memberkirnbas24-Aug-12 7:19 
QuestionBroken Image links Pin
Marcus Kramer7-Jun-12 5:53
memberMarcus Kramer7-Jun-12 5:53 
AnswerRe: Broken Image links Pin
kirnbas7-Jun-12 6:32
memberkirnbas7-Jun-12 6:32 
GeneralPlease show and explain the code Pin
PIEBALDconsult14-May-12 14:51
memberPIEBALDconsult14-May-12 14:51 
GeneralRe: Please show and explain the code Pin
kirnbas15-May-12 3:22
memberkirnbas15-May-12 3:22 
GeneralRe: Please show and explain the code Pin
PIEBALDconsult15-May-12 8:03
memberPIEBALDconsult15-May-12 8:03 
SuggestionQuite complicated expression evaluator... Pin
Andreas Gieriet14-May-12 13:18
memberAndreas Gieriet14-May-12 13:18 
Hello kirnbas,

your evaluator solution seems to me quite verbose and over-complicated.
You might have a look at Mathematical Expression Parser Using Coco/R[^] which provides two solutions:
A) writing a similar evaluator in about 100 lines of code by using[^]
B) writing the same evaluator, but hand crafted, in less than 150 lines of code

BTW: I also find that you should elaborate more on why you show us your trick - why should I red that? E.g. if talking about localized number scheme, then you must talk about the consequences and how you deal with these:
- What number formats exist (decimal point, thousand separator, ...)?
- How you deal with the ambiguities (you have to also localize the list separator)?
- Run the localization on kk-KZ, ky-KZ, en-US, de-DE, de-CH, sv-SE, sv-FI

The quirks on localization is that the coma is usually used as list separator (e.g. f(a,b)) as well as thousand separator (en-US) or as decimal separator (de-DE).

One approach is to allow the ambiguity and let the parser read greedily (letting the user to solve ambiguities by adding parenthesis, e.g. f((3,14159),(1,4142135))).
Another approach is to make the language not ambiguous and also take the list separator from the CultureInfo class (beside the thousand separator and the decimal separator).

At least this topic is worth an elaboration. That's why my vote of 3.

QuestionYou might want to elaborate on some of the inner workings, etc. Pin
ednrg14-May-12 9:07
memberednrg14-May-12 9:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 28 Feb 2014
Article Copyright 2012 by kirnbas
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid