How to evaluate a math expression contained in a string?

  • Thread starter Thread starter Juan
  • Start date Start date
J

Juan

If I have a string with a valid math expression like " (2 + 28)/1", how can
I evaluate it?



Thanks,

Juan.
 
I'm not sure how safe this is, but I used this in a non-production
environment and it works quite well:
 
Sorry about that, here's the code:

------------------------------------------------------------------------------
using System;

using Microsoft.JScript;
using Microsoft.JScript.Vsa;

namespace VPDBUtils
{
public class JScriptEvaluator
{
private static VsaEngine vsaEngine;

public static void Initialize()
{
vsaEngine = VsaEngine.CreateEngine();
}

public static void Close()
{
if (vsaEngine != null)
{
vsaEngine.Close();
}
}

private static object EvaluateString(string sStringToEvaluate)
{
return Eval.JScriptEvaluate(sStringToEvaluate, vsaEngine);
}

internal static double EvaluateStringAsDouble(string sStringToEvaluate)
{
return System.Convert.ToDouble(EvaluateString(sStringToEvaluate));
}
}
}
 
Back
Top