The attached class allows you to evaluate mathematical expressions with support for custom functions.
It is compatible with B4A, B4J and B4i.
Example:
Note that if you are using it with B4A then call Eval after Activity_Create completes (you can add Sleep(0) instead). Otherwise the Function event will not be raised.
Updates
V2.01 - Fixes an issue with sub-expressions converted to scientific notation (which is not supported).
V2.00 - adds support for custom functions.
It is compatible with B4A, B4J and B4i.
Example:
B4X:
Sub AppStart (Args() As String)
Dim e As B4XEval
e.Initialize(Me, "Eval")
Log(e.Eval("1 + Min(2, Max(-4, 1), 6)"))
Log(e.Eval("-(2+5)*(7-3) + Sin(15 + 15) + Cos(30)"))
Log("Error? " & e.Error)
Log(e.Eval("-(2+5)*-(7-3)"))
Log(e.Eval("-((-7-3))"))
Log(1.321/-2/3.123 + (2 * 2 + 3) + 4)
Log(e.Eval("1.321/-2/3.123 + (2 * 2 + 3) + 4"))
End Sub
'custom functions implementation
Sub Eval_Function (Name As String, Values As List) As Double
Select Name 'it will be lower case
Case "min"
Dim d As Double = Values.Get(0)
For Each n As Double In Values
If n < d Then d = n
Next
Return d
Case "max"
Dim d As Double = Values.Get(0)
For Each n As Double In Values
If n > d Then d = n
Next
Return d
Case "sin"
Return SinD(Values.Get(0))
Case Else
Log("Invalid function: " & Name)
Dim e As B4XEval = Sender
e.Error = True
Return 0
End Select
End Sub
Note that if you are using it with B4A then call Eval after Activity_Create completes (you can add Sleep(0) instead). Otherwise the Function event will not be raised.
Updates
V2.01 - Fixes an issue with sub-expressions converted to scientific notation (which is not supported).
V2.00 - adds support for custom functions.
Attachments
Last edited: