Question:
hello, I needed to resolve a string with an account (ex. 2 + 2) in C# and return an integer (ex. 4)
static void Main(string[] args)
{
string str = "2 + 2";
int resultado = Calcular(str);
Console.WriteLine("Resultado => {0}",resultado);
Console.ReadLine();
}
any tips?
Answer:
The NCalc library simplifies this for you. Install it from Nuget:
Install-Package ncalc
Then use it like this:
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();
}
}
}