How to Convert String Formula to a Mathematical Formula in C#

How to convert string formula to a mathematical formula in C#

Finally I got the FLEE library for this purpose. The tool is free and perfectly fit for your purpose.
Below is an example how to use this library:

// Define the context of our expression
ExpressionContext context = new ExpressionContext();
// Allow the expression to use all static public methods of System.Math
context.Imports.AddType(typeof(Math));
// Define an int variable
context.Variables["a"] = 100;
// Create a dynamic expression that evaluates to an Object
IDynamicExpression eDynamic = context.CompileDynamic("sqrt(a) + pi");
// Evaluate the expressions
double result = (double)eDynamic.Evaluate();

Given a string to convert for a math equation with variable c# .net core

You can't assign the result of equation to total because the equation may result into a decimal number and total is of type int.

using System.Data;

double result = Double.Parse(new DataTable().Compute($"{total}+{var.Replace("total", total+"")}", "")+"");

the concatenations with an empty string is to convert the object returned by Compute() method to string and int type (total) to string because the Double.Parse() method and Replace() methods expect a string in their parameters.

Converting string formula to mathematical formula in c#

You can use Shunting-yard algorithm to convert the expression to postfix notation or to ast directly. See this answer for nice explanation: Equation (expression) parser with precedence

How to convert a string c# equation to an answer

bcParser.NET is a safe eval() function to evaluate math formulas. bcParser.NET is a Math Parser Library for the .NET Platform. bcParser.NET parses and evaluates mathematical expressions given as strings at runtime.

MathParser.SetExpression("sin(3)+cos(3)");
double value = MathParser.getValueAsDouble();

Calculate math equation from string (+, -, /, *)

Fixed your problem by doing the following changes.

  1. Initialize your sum with the first number:

    double sum = double.Parse(keywords[0]);
  2. Change your for loop to a step of two and start the loop at 2

    for (int i = 2; i < keywords.Count - 1; i += 2)
  3. Change the keyword to get the it by i - 1

    string keyword = keywords[i - 1];

Those changes will give the result 27.

Here is the complete code:

private static double Parse(string ParseEquation)
{
string[] split = Regex.Split(ParseEquation, @"(?<=[+-/*])");

List<string> keywords = new List<string>();

foreach (string i in split)
{
var var1 = Regex.Match(i, @"\d+").Value;
keywords.Add(var1);

var var2 = Regex.Match(i, @"([+-/*])").Value;
keywords.Add(var2);
}

double sum = double.Parse(keywords[0]);

for (int i = 2; i < keywords.Count - 1; i += 2)
{
string keyword = keywords[i - 1];

if (keyword == "+")
sum = Addition(sum, double.Parse(keywords[i]));
else if (keyword == "-")
sum = Subtraction(sum, double.Parse(keywords[i]));
else if (keyword == "/")
sum = Division(sum, double.Parse(keywords[i]));
else if (keyword == "*")
sum = Multiplication(sum, double.Parse(keywords[i]));
}
return sum;
}

How to convent string math formula to int at run time in c#

@Rand Random, @Charlieface

First of all, if you come across a question in a language you don't know, I recommend you to skip it. Do not create invalid claims!

int.parse(); is used to
convert a string integer to an integer value.

But clearly in this case this line =>

int value = int.parse(code);  // value should be 2

case's an error,
(because code is not an integer)

And to do what I was asking u don't need a compiler. I actually did it without it!!

    using static System.Math;
using Project = System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class YesICanWithoutACompiler
{
static void Main(string[] args)
{

string code = "1+ 1 + 1*1 * (((((((3!=63))?(2==4?5:1):7))==8)?2:(4==6?7:3) ))";

string formula = getFormular(code); // outputs: 1+ 1 + 1*1 * (3)

Console.WriteLine("yes I can!: " + new System.Data.DataTable().Compute(formula, ""));
Console.ReadLine();

}
static int IndexOfAny(string source, string[] items, int startat = 0)
{
List<int> indexes = new List<int>();
for (int f = 0; f < items.Length; f++)
{
int loo = source.IndexOf(items[f], startat);
if (loo != -1)
{
indexes.Add(loo);
}
}

if (indexes.Count > 0)
{
return indexes.Min();
}
else
{
return -1;
}


}


static bool conditoin(int x, string mark, int y)
{
switch (mark)
{
case "!=":
return (x != y);
case "==": return (x == y);
case ">=": return (x >= y);
case "<=": return (x <= y);
default: return false;
}

}

static string getFormular(string code)
{
int ind = IndexOfAny(code, new string[] { "==", ">=", "<=", "!=" });

while (ind != -1)
{



int condition1 = int.Parse(string.Join("", code.Substring(0, ind).Reverse().SkipWhile(c => !char.IsDigit(c)).TakeWhile(d => char.IsDigit(d))));
string conditioin = code.Substring(ind, 2);

int condition2 = int.Parse(string.Join("", code.Substring(ind + 2).TakeWhile(d => char.IsDigit(d))));


string arvo = "";
if (conditoin(condition1, conditioin, condition2))
{
arvo = code.Substring(1 + code.IndexOf("?", ind + 2)).Trim();

if (arvo.StartsWith("("))
{


int ndent = 1;
int h = 0;
while (h < arvo.Length && ndent != 0)
{
h++;


if (arvo[h] == ')') ndent--;
if (arvo[h] == '(') ndent++;
}

arvo = arvo.Substring(0, h + 1);


}
else
{
arvo = string.Join("", arvo.TakeWhile(s => s != ':'));

}



}
else
{

arvo = code.Substring(1 + code.IndexOf(":", ind + 2)).Trim();

if (arvo.StartsWith("("))
{


int ndent = 1;
int h = 0;
while (h < arvo.Length && ndent != 0)
{
h++;


if (arvo[h] == ')') ndent--;
if (arvo[h] == '(') ndent++;
}

arvo = arvo.Substring(0, h + 1);

}
else
{
arvo = string.Join("", arvo.TakeWhile(s => s != ')'));

}








}

int f = code.IndexOf("?", ind);
int indent = 0;
while (f > 0 && indent != -1)
{
f--;
if (code[f] == ')') indent++;
if (code[f] == '(') indent--;
}

int t = f;
indent = 1;

while (t < code.Length && indent != 0)
{
t++;
if (code[t] == ')') indent--;
if (code[t] == '(') indent++;
}

code = code.Remove(f, (t - f) + 1).Insert(f, arvo);

ind = IndexOfAny(code, new string[] { "==", ">=", "<=", "!=" });

}
return code;
}

}


Related Topics



Leave a reply



Submit