interpret account in string C #

4

Hello, I needed to resolve a string with an account (eg 2 + 2) in C # and return an integer (eg 4)

static void Main(string[] args)
{
    string str = "2 + 2";
    int resultado = Calcular(str);
    Console.WriteLine("Resultado => {0}",resultado);
    Console.ReadLine();
}

Any tips?

    
asked by anonymous 16.07.2017 / 18:56

2 answers

3

The NCalc library simplifies this for you. Install it from Nuget:

Install-Package ncalc

Then use it this way:

using NCalc;
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "2 + 2";
            var expressao = new Expression(str);
            Console.WriteLine("Resultado => {0}", expressao.Evaluate());
            Console.ReadLine();
        }
    }
}
    
16.07.2017 / 19:09
1

I use the following function:

        /// <summary>
    /// Calcular Formulas
    /// </summary>
    /// <param name="evaluationString"></param>
    /// <returns></returns>
    public static string CalculateFormula(string evaluationString)
    {
        Microsoft.JScript.Vsa.VsaEngine en = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
        Object result = Microsoft.JScript.Eval.JScriptEvaluate(evaluationString, en);

        return result.ToString();
    }
    
16.07.2017 / 19:13