Tips and tricks for .NET using ASP and VB code.

Evaluate math expression from text

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Dim OnePlusOne As Double = EvaluateExpression("1+1")
        Dim SixMinusTwo As Double = EvaluateExpression("6-2")
        Dim EightDividedByFour As Double = EvaluateExpression("8/4")
        Dim FifteenSixteenths As Double = EvaluateExpression("15/16")
        Dim RemainderOfFiveDividedByTwo As Double = EvaluateExpression("5%2")
        Dim MultipleExpressions As Double = EvaluateExpression("(1+1)*(6-2)-(8/4)/(15/16)")
        Dim InvalidOperation As Double = EvaluateExpression("0/0")
    End Sub

    Function EvaluateExpression(ExpressionString As String) As Double
        Dim ReturnValue As Double = Nothing
        Dim ComputeDataTable As New Data.DataTable
        Try
            ReturnValue = Convert.ToDouble(ComputeDataTable.Compute(ExpressionString, Nothing))
            'Can only evaluate using the following arithmetic operations:
            '+ (addition), - (subtraction), * (multiplication), / (division), % (modulus)
        Catch
        End Try
        Return ReturnValue
    End Function

No comments:

Post a Comment

Search This Blog