Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate string with math operators [duplicate]

Is there an easy way to evaluate strings like "(4+8)*2" So that you'd get the int value of 24?

Or is there a lot of work needed to get this done...?

like image 560
Mark Lalor Avatar asked Apr 30 '11 01:04

Mark Lalor


People also ask

Can you do math operations on strings in Python?

You can use the eval function to evaluate mathematical expressions in strings.

How do you convert a string to arithmetic operator?

var myString = "225 + 15 - 10" var newString = myString. split(" "); This would turn myString into an array: ["225", "+", "15", "-", "10"];


1 Answers

Someone else added this and then it got deleted. I thought it was pretty cool because no 3rd party libraries required.

class Program
    {

        static void Main(string[] args)
        {
            Console.WriteLine(Evaluate("(4+8)*2"));
            Console.ReadKey();
        }

        public static double Evaluate(string expression)
        {
            DataTable table = new DataTable();
            table.Columns.Add("expression", typeof(string), expression);
            DataRow row = table.NewRow();
            table.Rows.Add(row);
            return double.Parse((string)row["expression"]);
        }

    } 
like image 99
Richard Brightwell Avatar answered Oct 19 '22 17:10

Richard Brightwell