• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
3
Question by ericksson · Nov 17, 2010 at 12:57 PM · convert

How to evaluate a mathematical expression in Unity's C#

Is there an javascript-like Evaluate() function in C# or any other similar method?

I have a simple mathematical expression (no brackets, only -, +, / and * operands) stored in a string and I want to be able to evaluate that and get the result in a float.

Example: For the input string "2+3-5*7" the output should be -30.

I tried to implement a method myself, but I have troubles converting a character to an int. It seems like I get the ASCII code of the character in my int instead of the value I want.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
6
Best Answer

Answer by ericksson · Nov 17, 2010 at 06:24 PM

I found what I was looking for here: http://www.logiclabz.com/c/evaluate-function-in-c-net-as-eval-function-in-javascript.aspx

The method that works in Unity is:

 public static double Evaluate(string expression)  
 {  
     return (double)new System.Xml.XPath.XPathDocument  
     (new System.IO.StringReader("< r />")).CreateNavigator().Evaluate  
     (string.Format("number({0})", new  
     System.Text.RegularExpressions.Regex(@"([\+\-\*])").Replace(expression, " ${1} ").Replace("/", " div ").Replace("%", " mod ")));  
 } 
             

Comment
Add comment · Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image a436t4ataf · Nov 04, 2014 at 05:32 PM 0
Share

That webpage has been deleted, is now just advertising.

Can you explain WHAT you did above?

avatar image Bunny83 · Nov 04, 2014 at 06:00 PM 0
Share

@a436t4ataf:
Well, i'm actually a regular expression noob but it looks like

 new System.Text.RegularExpressions.Regex(@"([\+\-\*])").Replace(expression, " ${1} ").Replace("/", " div ").Replace("%", " mod ")

Simply reformats your expression string to have a space before and after each operator. It also replaces "/" with "div" and "%" with "mod".

I'm also not very familiar with XPath, but

 new System.Xml.XPath.XPathDocument(new System.IO.StringReader("<r/>"))

will create an XPath document with one element < r />. On that object he calls GetNavigator and on the returned navigator Evaluate. To that method he basically passes the string: "number(" + your expression + ")" which most likely will be evaluated to a number by the Evaluate method. The result is casted to double and returned.

So if you input something like "5*6/2+5" will be reformatted as "number(5 * 6 div 2 + 5)" and evaluated by the Evaluate method of that XPathDocument's navigator ^^

So in a more sequential and more readable version it would look like this:

     public static double Evaluate(string expression)
     {
         var doc = new System.Xml.XPath.XPathDocument(new System.IO.StringReader("<r/>"));
         var nav = doc.CreateNavigator();
         var newString = expression;
         newString = (new System.Text.RegularExpressions.Regex(@"([\+\-\*])")).Replace(newString, " ${1} ");
         newString = newString.Replace("/", " div ").Replace("%", " mod ");
         return (double)nav.Evaluate("number(" + newString + ")");
     } 
avatar image a436t4ataf · Nov 05, 2014 at 12:50 AM 0
Share

OP has a strange regexp. Replace "new Sytem.Text...*])") with the string you want to evaluate, and this works.

avatar image Bunny83 · Nov 05, 2014 at 04:16 AM 0
Share

@a436t4ataf: Well, it isn't that strange, he just has one thing wrong. "-" is a special character and need to be escaped. I'll fix my comment to reflect that ;)

edit
Correction, he actually has excaped all 3 characters, but since it's an old question it was formatted with < code >< pre > which seems to eat the backslash. When you edit the answer (which i did) you can see they are actually there. I fixed the code highlighting

avatar image AbdulRaman · Jun 04, 2018 at 09:26 AM 0
Share

it doesn't work with me it gives me this error XmlException: a name did not start with a legal character 32 ( ) Line 1, position 2. $$anonymous$$ono.Xml2.XmlTextReader.ReadName (System.String& prefix, System.String& localName) $$anonymous$$ono.Xml2.XmlTextReader.ReadStartTag () $$anonymous$$ono.Xml2.XmlTextReader.ReadContent () $$anonymous$$ono.Xml2.XmlTextReader.Read () System.Xml.XmlTextReader.Read () $$anonymous$$ono.Xml.EntityResolvingXmlReader.Read () $$anonymous$$ono.Xml.DTDValidatingReader.ReadContent () $$anonymous$$ono.Xml.DTDValidatingReader.Read () $$anonymous$$ono.Xml.Schema.XsdValidatingReader.Read () System.Xml.XmlValidatingReader.Read () $$anonymous$$ono.Xml.XPath.DT$$anonymous$$XPathDocumentBuilder2.Compile () $$anonymous$$ono.Xml.XPath.DT$$anonymous$$XPathDocumentBuilder2.Init (System.Xml.XmlReader reader, XmlSpace space, Int32 defaultCapacity) $$anonymous$$ono.Xml.XPath.DT$$anonymous$$XPathDocumentBuilder2..ctor (System.Xml.XmlReader reader, XmlSpace space, Int32 defaultCapacity) $$anonymous$$ono.Xml.XPath.DT$$anonymous$$XPathDocumentBuilder2..ctor (System.Xml.XmlReader reader, XmlSpace space) System.Xml.XPath.XPathDocument.Initialize (System.Xml.XmlReader reader, XmlSpace space) System.Xml.XPath.XPathDocument..ctor (System.IO.TextReader reader) Game$$anonymous$$anager.Evaluate (System.String expression) (at Assets/Scripts/Game$$anonymous$$anager.cs:110) Game$$anonymous$$anager.EquationGenerator () (at Assets/Scripts/Game$$anonymous$$anager.cs:102) Game$$anonymous$$anager.Update () (at Assets/Scripts/Game$$anonymous$$anager.cs:51)

avatar image Bunny83 AbdulRaman · Jun 04, 2018 at 12:05 PM 0
Share

Do you use the version in the answer or the one i posted in the comment? I guess it might be the spaces in "< r />". Try using "<r/>".


Though i would recommend to use a different solution. Using System.Xml will add quite a bit of overhead since the whole System.Xml.dll will be shipped with your game (if i remember correctly it was about 0.5 $$anonymous$$B). I've written a simple expression parser which i've linked in the comment below.

avatar image
0

Answer by Herman-Tulleken · Nov 17, 2010 at 02:49 PM

Some more info here:

http://stackoverflow.com/questions/4629/c-eval-equivalent

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by satan_6_6_6 · Nov 13, 2015 at 09:53 PM

https://github.com/akuukka/ExpressionSolver

This one does the trick.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Bunny83 · Nov 14, 2015 at 05:13 AM 0
Share

I've written a similar parser a year ago. If you have a working Unity webplayer installed you can test it here. It evaluates the expression 2000 times each frame and draws a line between the results. "x" goes from -1 to 1

avatar image satan_6_6_6 Bunny83 · Nov 26, 2015 at 07:21 PM 0
Share

I've used that one and it works pretty well.

Noticed a few problems though: you check variable/function names with StartsWith and therefore if you have variables temp and temp2, temp2 gets treated as temp which results in very unexpected behaviour.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Can someone help me fix my Javascript for Flickering Light? 6 Answers

Setting Scroll View Width GUILayout 1 Answer

cannot implicitly convert type void to bool 1 Answer

Material doesn't have a color property '_Color' 4 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges