Click here to Skip to main content
15,891,981 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI,
I have below like i need to calculate below using c#.net

String Numbers="5+10+5+22+22.5-10";
Can U guide or send snippets
Posted

Solutions provided by Mehdi Gholam and CIDev is quite good but i would like to show you some alternative and simple code that would not require any 3rd party library! Let's see:
C#
class Program
{
    const string expressionColumn = "expression";

    public static void Main(string[] args)
    {
        Console.WriteLine(Evaluate("5+10+5+22+22.5-10"));
    }

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


Cheers!
Shuvro
 
Share this answer
 
v4
Comments
BillW33 17-Sep-13 16:40pm    
DataTable parse is a good one, +5
ridoy 17-Sep-13 16:42pm    
your pleasure,thank you.
Sergey Alexandrovich Kryukov 17-Sep-13 23:42pm    
Amazing. I voted 5, but there are few minor problems: 1) declare "expression" an explicit constant; not only it is hard-code, but also repeated twice, this is a big sin, unsupportable; 2) I would change "expression" to some other string, to avoid suggesting to some, say, naive reader that the name of the method parameter is related to its name; 3) remove "public"; there are practically no situation where the method of class of the entry point "Main" could be used in other assemblies; leave it private; 4) maybe show the declaring class of the two methods (like "Program"), to make the demo less confusing.
—SA
ridoy 18-Sep-13 2:35am    
Thanks for your valuable suggestion SA,was in a hurry,hence edited now,:).
Sergey Alexandrovich Kryukov 18-Sep-13 9:55am    
Very nice. Again, very interesting sharp answer.
—SA
Besides the one mentioned by Mehdi Gholam there are:
Calculator.Net[^]
NCalc[^]
MuParser[^]
Math Parser .NET[^]
and Google knows lots more[^]
 
Share this answer
 
Comments
ridoy 17-Sep-13 16:37pm    
NCalc is really awesome,5ed. check my alternate solution,:).
 
Share this answer
 
Comments
ridoy 17-Sep-13 16:36pm    
5ed! check my alternate solution,:).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900