Evaluate mathematical expression from a string using VB - vb.net

I want to calculate a arithmetic expression from a string using VB, any ideas ?
As an example : "x+2" from a textbox, I want to evaluate the expression

Dim equation As String = "2+6/2"
Dim result = New DataTable().Compute(equation, Nothing)

you can use NCalc for this. It also accepts parameters like x, y, z,...
Dim e As Expression = new Expression("2 + 3 * 5")
Msgbox(17 = e.Evaluate())

You can use mxparser library for this purpose.Give a reference to mxparser.dll in your project by clicking ADD Reference button of Microsoft Visual Studio.The mxparser library source code or latest dll file can be from www.mathparser.org.The mXparser is a Math Parser for Java, Android, C# .NET (CLS) Libraries.
Imports org.mariuszgromada.math.mxparser
Private Function evaluate(ByVal str As String) AS Double
Dim expr As Expression = New Expression(str)
DIM d1 As Double
d1=0
d1=expr.calculate()
return d1
End Function
Call to the function can be as follows.
DIM str as String
str=""
str=((45^5)/45))*(5*6)
Dim d as Double
d=0
d=evaluate(str)
MsgBox(" The result of the expression is " + d.ToString)

Related

Equivalent of function String$() VB.Net?

I am migrating an application from VB6 to VB.Net, Which is using the String$() function.
My question is: Which is the "equivalent" of VB6 String$() in following Code?
Dim Symbol As String=""
Dim iRet As Long
iRet = GetLocaleInfo(LCID, LOCALE_SCURRENCY, lpLCDataVar, 0)
Symbol = String$(iRet, 0)
Note that String$() is the function which returns a repeating character string of the length specified:
Syntax:
String$(number, character)
number Length of the returned string.
character Required. Character
code specifying the character or string expression whose first
character is used to build the return string.
(reference)
If I will remove $, It will give me error that "String" is a Class and cannot used as an expression.
This String constructor is the correct way to create a String containing a specific number of a specific character, e.g.
Dim c = "0"c
Dim count = 10
Dim str As New String(c, count)
The equivalent to String$ (in older BASICs) is StrDup (VB.NET).
So, in your case:
Symbol = StrDup(iRet, Chr(0))
The code appears to be getting the currency symbol (and decimal separator) for a culture. It would be better to write it using .NET methods instead of the half-way route of using VB6 in .NET.
For example,
Imports System.Globalization
Module Module1
Sub Main()
Dim lcid = 2057
Dim ci As New CultureInfo(lcid)
Console.WriteLine(ci.EnglishName)
Console.WriteLine(ci.NumberFormat.CurrencySymbol)
Console.WriteLine(ci.NumberFormat.NumberDecimalSeparator)
Console.ReadLine()
End Sub
End Module
outputs
English (United Kingdom)
£
.
There is much more information in the documentation for the CultureInfo Class.

I wrote a code which reverses a string (and it does), but I don't think it's the clean/right way to do it

I wanted to get familiar with the built-in functions of VB, specifically, the len() function.
However, I think this may not be the right way to concatenate a string with a char.
Also, it may interest you that the error list says,
"Warning 1 Variable 'reverse' is used before it has been assigned a
value. A null reference exception could result at runtime."
I executed the program but it ran fine. Here's the code:
Sub Main()
Dim a As String
Console.WriteLine("Enter the value of the string you want to reverse: ")
a = Console.ReadLine()
Dim reverse As String
Dim temp As Char
Dim str As Integer
str = Len(a)
For x = str To 1 Step -1
temp = Mid(a, x)
reverse = reverse + temp
Next x
Console.WriteLine(reverse)
Console.ReadKey()
End Sub
I'm still learning this language and so far it's been really fun to make small programs and stuff.
Dim TestString As String = "ABCDEFG"
Dim revString As String = StrReverse(TestString)
ref: https://msdn.microsoft.com/en-us/library/e462ax87(v=vs.90).aspx
You are getting the warning
"Warning 1 Variable 'reverse' is used before it has been assigned a
value. A null reference exception could result at runtime."
Because String variable reverse is not yet initialized. Compiler will consider the scenario that For is not executing in such situation the reverse can be null. you can get out of the warning by assigning an empty value to the string: ie.,
Dim reverse As String=String.Empty
You can do the functionality in the following ways too:
Dim inputStr As String = String.Empty
Console.WriteLine("Enter the value of the string you want to reverse: ")
inputStr = Console.ReadLine()
Dim reverse As String = String.Join("", inputStr.AsEnumerable().Reverse)
Console.WriteLine(reverse)
Console.ReadKey()
OR
Dim reverse As String = String.Join("", inputStr.ToCharArray().Reverse)

writing arabic numbers Into Visual Studio

I have a little but headbrick problem which consists on assigning arabic numbers into string.
What I try to write into my program is like below :
Dim TestDebt As Double = 4456.438
Dim TestString As String = FormatCurrency(TestDebt)
If TestString <> "ر.س.‏4,456.44" Then
Check_System_params = False
Exit Function
End If
But into my Visual Studio IDE, It is Written like :
Which setting should I change to be able to write the desired string (without the ? caracters)
Thank you
As it is an issue of Editor I did as follow ( I convert Strings to Windows 1256 and don't make attention at what is written in the IDE) :
Public Shared Function Utf8_TO_1256(ByVal read As String) As String
Dim rawBytes As Byte() = System.Text.Encoding.Default.GetBytes(read)
Dim converted As New String(System.Text.Encoding.GetEncoding(1256).GetChars(rawBytes))
Return converted.ToString
End Function

How to convert a string expression to vb code?

I have a string output from user interface as below,
strFormula ="gridControlName.Rows(i).cells("C1").value *
gridControlName.Rows(i).cells("C2").value"
if i write code like
dblRes=gridControlName.Rows(i).cells("C1").value *
gridControlName.Rows(i).cells("C2").value
it will give result.. but since its a string i could not get result
How can I remove the double quotes from the above string and get the values entered in the grid cells to be multiplied?
I don't think there's an 'easy' way to do this, since VB.Net doesn't have an "eval()" like some other languages. However, it does support run-time compilation. Here are a couple articles which may help you:
Using .NET Languages to make your Application Scriptable (VB.Net example)
Runtime Compilation (A .NET eval statement) (C# example)
Both are intended to be a bit more robust than just executing single lines of code, allowing users to input entire textboxes of their own code for example, but should give you some direction. Both include sample projects.
Hi guys thanks for your updates.. I wrote my own function by using your concepts and some other code snippets .I am posting the result
Function generate(ByVal alg As String, ByVal intRow As Integer) As String Dim algSplit As String() = alg.Split(" "c)
For index As Int32 = 0 To algSplit.Length - 1
'algSplit(index) = algSplit(index).Replace("#"c, "Number")
If algSplit(index).Contains("[") Then
Dim i As Integer = algSplit(index).IndexOf("[")
Dim f As String = algSplit(index).Substring(i + 1, algSplit(index).IndexOf("]", i + 1) - i - 1)
Dim grdCell As Infragistics.Win.UltraWinGrid.UltraGridCell = dgExcelEstimate.Rows(intRow).Cells(f)
Dim dblVal As Double = grdCell.Value
algSplit(index) = dblVal
End If
Next
Dim result As String = String.Join("", algSplit)
'Dim dblRes As Double = Convert.ToDouble(result)
Return result
End Function
Thanks again every one.. expecting same in future

Mixed Encoding to String

I have a string in VB.net that may contain something like the following:
This is a 0x000020AC symbol
This is the UTF-32 encoding for the Euro Symbol according to this article http://www.fileformat.info/info/unicode/char/20ac/index.htm
I'd like to convert this into
This is a € symbol
I've tried using UnicodeEncoding() class in VB.net (Framework 2.0, as I'm modifying a legacy application)
When I use this class to encode, and then decode I still get back the original string.
I expected that the UnicodeEncoding would recognise the already encoded part and not encode it against. But it appears to not be the case.
I'm a little lost now as to how I can convert a mixed encoded string into a normal string.
Background: When saving an Excel spreadsheet as CSV, anything outside of the ascii range gets converted to ?. So my idea is that if I can get my client to search/replace a few characters, such as the Euro symbol, into an encoded string such as 0x000020AC. Then I was hoping to convert those encoded parts back into the real symbols before I insert to a SQL database.
I've tried a function such as
Public Function Decode(ByVal s As String) As String
Dim uni As New UnicodeEncoding()
Dim encodedBytes As Byte() = uni.GetBytes(s)
Dim output As String = ""
output = uni.GetString(encodedBytes)
Return output
End Function
Which was based on the examples on the MSDN at http://msdn.microsoft.com/en-us/library/system.text.unicodeencoding.aspx
It could be that I have a complete mis-understanding of how this works in VB.net. In C# I can simply use escaped characters such as "\u20AC". But no such thing exists in VB.net.
Based on advice from Heinzi I implemented a Regex.Replace method using the following code, this appear to work for my examples.
Public Function Decode(ByVal s As String) As String
Dim output As String = ""
Dim sRegex As String = "0x[0-9a-zA-Z]{8}"
Dim r As Regex = New Regex(sRegex)
Dim myEvaluator As MatchEvaluator = New MatchEvaluator(AddressOf HexToString)
output = r.Replace(s, myEvaluator)
Return output
End Function
Public Function HexToString(ByVal hexString As Match) As String
Dim uni As New UnicodeEncoding(True, True)
Dim input As String = hexString.ToString
input = input.Substring(2)
input = input.TrimStart("0"c)
Dim output As String
Dim length As Integer = input.Length
Dim upperBound As Integer = length \ 2
If length Mod 2 = 0 Then
upperBound -= 1
Else
input = "0" & input
End If
Dim bytes(upperBound) As Byte
For i As Integer = 0 To upperBound
bytes(i) = Convert.ToByte(input.Substring(i * 2, 2), 16)
Next
output = uni.GetString(bytes)
Return output
End Function
Have you tried:
Public Function Decode(Byval Coded as string) as string
Return StrConv(Coded, vbUnicode)
End Function
Also, your function is invalid. It takes s as an argument, does a load of stuff and then outputs the s that was put into it instead of the stuff that was processed within it.