Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Converting a string into a number.

107 views
Skip to first unread message

John S. Ford

unread,
Nov 2, 2002, 5:55:29 PM11/2/02
to
Does anyone know of a method in VB .NET that will take a string representing
a valid numeric expression and convert it into a number (integer, long,
double, etc.)? For example:

Dim Answer as Double
Answer = Function("(10 + 6) / 8")

where Answer gets the value 2. I seem to recall a function that could do
this in VBA. Thanks in advance!

John


Haitham Salama

unread,
Nov 3, 2002, 4:31:28 AM11/3/02
to
If i understood you correctly you can use easly Cint, Cdbl or you can use
Value(string expression)

Hope is that what you are asking for

Haitham Salama
MCP, MCSD, MCDBA
Applications Development Manager
Miraco Carrir (Egypt)

"John S. Ford" <johnsfor...@hotmail.com> wrote in message
news:e#FHiDsgCHA.1996@tkmsftngp10...

Tom Scales

unread,
Nov 3, 2002, 7:33:18 AM11/3/02
to
Cdbl will do the calculation in a string that contains "(10 + 6) / 8" and
return 2?

That's cool!

Tom
"Haitham Salama" <Haitham...@miraco.com.eg> wrote in message
news:#iIFluxgCHA.2256@tkmsftngp12...

John S. Ford

unread,
Nov 3, 2002, 11:33:25 AM11/3/02
to
Dear Haitham,

CInt and CDbl both throw exceptions:

"Cast from string "(10 + 6)/8" to type 'Integer' is not valid." or "Cast
from string "(10 + 6)/8" to type 'Double' is not valid."

the Value() function you mentioned doesn't appear to be supported by Visual
Basic .NET. Is there a namespace I have to import before I can use it?

John

"Haitham Salama" <Haitham...@miraco.com.eg> wrote in message
news:#iIFluxgCHA.2256@tkmsftngp12...

Chris Balmer

unread,
Nov 3, 2002, 12:19:43 PM11/3/02
to
Well, the advice so far isn't right. CLng and Cdbl make a
string numeral into a long or double (Like "10" or "10.5"
but not "10 + 1"). What you have to do is compute the
code, this is what I did to calculate your expression and
output the result 2:

Dim dtCalculator As New System.Data.DataTable()
MsgBox(dtCalculator.Compute("((10 + 6) / 8)", ""))

Just make sure you have closing braces or you will get an
exception.

-Chris

>.
>

John S. Ford

unread,
Nov 3, 2002, 12:48:07 PM11/3/02
to
Dear Chris,

That worked perfectly but Jeez! How was I supposed to find that solution?
I can't seem to figure out how to research these problems on my own through
the .NET Framework. How did you find that answer?

John

"Chris Balmer" <balm...@msu.edu> wrote in message
news:4bf501c2835d$336269c0$36ef2ecf@tkmsftngxa12...

Chris Balmer

unread,
Nov 3, 2002, 12:52:36 PM11/3/02
to
Well I had the same problem, not being able to find a
solution that it. Your question intriqued me because I
knew there had to be a way to do it. So while waiting on
a few computers here at work to finish loading stuff I
spent a minute or two in VB.NET finding a solution for
you. First I did a search on "process code at runtime"
which got me no where. So I looked in the object browser
and started searching the framework. With the find
feature I looked for "math" which only got me a math
library, then I tried "compute" which got the function
you needed. Its just luck of the draw I was able to find
it I guess :-). But I wrote it down for when I get time
to work on the source code area on my company website. I
looked through the newsgroup and a lot of people ask for
it and have to use tricky things to do it. I think those
two lines make it nice, clean and simple :-).

-Chris Balmer

>.
>

John S. Ford

unread,
Nov 3, 2002, 3:59:21 PM11/3/02
to
Dear Chris,

Thanks for the help. Unfortunately, this technique doesn't seem to work
with the exponentiation operator ("^"). It doesn't recognize expressions
such as 5 ^ 2 let alone trig functions. Still doesn't work even if I import
the System.Math namespace. Any other ideas?

John


"Chris Balmer" <balm...@msu.edu> wrote in message

news:55c201c28361$cb0230e0$2ae2...@phx.gbl...

Jason Sobell (iGadget)

unread,
Nov 3, 2002, 5:05:26 PM11/3/02
to
How often do you plan to do this, and how powerful are your expressions
going to be?
If you want a macro language, you can do this directly in VB.NET. I've
attached a copy of the code section from a simple VB.NET macro editor I was
working on. You could adapt it to your requirements, but I don't know how it
will fare if you have to call it thousands of times :)

Cheers,
Jason

"John S. Ford" <johnsfor...@hotmail.com> wrote in message

news:#vBLUn3gCHA.1516@tkmsftngp09...


> Dear Chris,
>
> Thanks for the help. Unfortunately, this technique doesn't seem to work
> with the exponentiation operator ("^"). It doesn't recognize expressions
> such as 5 ^ 2 let alone trig functions. Still doesn't work even if I
import
> the System.Math namespace. Any other ideas?

[Snip]

--------------------

Dim results As CompilerResults

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdBuild.Click

Dim vbProvider As VBCodeProvider = New VBCodeProvider()
Dim compiler As ICodeCompiler = New
VBCodeProvider().CreateCompiler()
Dim parameters As CompilerParameters = New CompilerParameters()

parameters.GenerateInMemory = True

parameters.ReferencedAssemblies.Add("System.dll")

parameters.ReferencedAssemblies.Add("Microsoft.VisualBasic.Compatibility.dll
")
parameters.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
parameters.WarningLevel = 99

results = compiler.CompileAssemblyFromSource(parameters, _
"Imports System" +
vbCrLf + _
"Imports
Microsoft.VisualBasic" + vbCrLf + _
"NameSpace QED" + vbCrLf
+ _
"Class Macro" + vbCrLf +
_
Me.SourceCode.Text +
vbCrLf + _
"End Class" + vbCrLf + _
"End Namespace")


lstErrors.Items.Clear()
If results.Errors.Count > 0 Then
Dim cError As CompilerError
For Each cError In results.Errors
lstErrors.Items.Add(cError.ToString)
Next
Else
lstErrors.Items.Add("Compile successful")
End If

End Sub

Private Sub cmdRun_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdRun.Click
Dim ass As [Assembly]
ass = results.CompiledAssembly
Dim t As Type
t = ass.GetType("QED.Macro")
Dim o As Object
o = Activator.CreateInstance(t)
Dim res As Object
res = o.GetType().GetMethod("Test").Invoke(Nothing, Nothing)
Console.WriteLine(res.ToString())
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

SourceCode.Text = _
" Shared Function Test() as String" + vbCrLf + _
" Console.WriteLine(""From Main"")" + vbCrLf + _
" Return(""Jason"")" + vbCrLf + _
" End Function"

End Sub


Stephen Kent

unread,
Nov 4, 2002, 9:54:31 AM11/4/02
to
If I remember correctly then I believe the function you should use is
something like Evaluate or Eval and I think the function is part of the
scripting runtime (scrrun.dll). Hope this helps (I'm pulling this off the
top of my head).

Stephen Kent

"John S. Ford" <johnsfor...@hotmail.com> wrote in message

news:e#FHiDsgCHA.1996@tkmsftngp10...

Steve

unread,
Nov 4, 2002, 10:20:04 PM11/4/02
to
Add a reference to MSScriptControl, then send your expression to this
function (courtesy of "Mastering VB.NET" Ch. 14, "FunctionPlotting")

Function Function1Eval(ByVal X As Double) As Double

Try

AxScriptControl1.ExecuteStatement("X=" & X)

Function1Eval = CSng(AxScriptControl1.Eval(txtFunction1.Text))

Catch exc As Exception

Throw New Exception("Can't evaluate function at X=" & X)

End Try

End Function

"Stephen Kent" <sk...@l3digital.com> wrote in message
news:#nEfUFBhCHA.2508@tkmsftngp08...

Ravichandran J.V.

unread,
Nov 5, 2002, 1:22:11 AM11/5/02
to
The easiest conversion technique is

int i=val(string).

with regards,

J.V.Ravichandran

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

John S. Ford

unread,
Nov 5, 2002, 7:14:07 AM11/5/02
to
Sorry Ravichandron. The Val function doesn't evalute the expression
expressed in a string. It merely extracts the numbers from it (at least in
Visual Basic .NET).

John

"Ravichandran J.V." <jvravic...@yahoo.com> wrote in message
news:#CS9tOJhCHA.2472@tkmsftngp12...

Tom Shelton

unread,
Nov 5, 2002, 11:20:50 AM11/5/02
to

"John S. Ford" <johnsfor...@hotmail.com> wrote in message
news:e#FHiDsgCHA.1996@tkmsftngp10...

John,

Here is an idea, that would avoid using COM interop... JScript has an eval
function that will do just what your doing, in fact it will run snippets of
arbitrary JScript code. So here is what I suggest (since the MS Scripting
Runtime is often turned off, and because you should avoid COM interop if
possible) - make a dll in JScript that exposes the Eval function for you...
You could do something like this:

1. Create a class in JScript:

// JScript source code
class EvalClass
{
function Evaluate(expression)
{
return eval(expression);
}
}


2. Compile it to a dll:

jsc /target:library evaluator.js ' Compiles to evaluator.dll

3. Reference evaluator.dll and Microsoft.JScript.dll in your VB project.

4. Write code that looks like this:

Dim ec As New EvalClass()
Dim expr As String = "(10 + 6) / 8"
Dim res As Double = CType(ec.Evaluate(expr), Double)

Console.WriteLine("{0} = {1}", expr, res)

You gotta love .NET!

HTH,
Tom Shelton


Tom Shelton

unread,
Nov 5, 2002, 11:14:29 AM11/5/02
to

> > "John S. Ford" <johnsfor...@hotmail.com> wrote in message
> > news:e#FHiDsgCHA.1996@tkmsftngp10...
> > > Does anyone know of a method in VB .NET that will take a string
> > representing
> > > a valid numeric expression and convert it into a number (integer,
long,
> > > double, etc.)? For example:
> > >
> > > Dim Answer as Double
> > > Answer = Function("(10 + 6) / 8")
> > >
> > > where Answer gets the value 2. I seem to recall a function that could
> do
> > > this in VBA. Thanks in advance!
> > >
> > > John

John,

clintonG

unread,
Nov 8, 2002, 9:35:19 PM11/8/02
to
This is a perfect example why VB developers should cut the
apron strings and learn C#. None of this garbage applies.

I mean it, I'm just a lowly script kiddie and C# is making so
much sense to me I can't believe how unjustified my former
concerns were.

--
<%= Clinton Gallagher
A/E/C Consulting, Web Design, e-Commerce Software Development
Wauwatosa, Milwaukee County, Wisconsin USA
NET csgal...@REMOVETHISTEXTmetromilwaukee.com
URL http://www.metromilwaukee.com/clintongallagher/

LaGarde StoreFront 5 Affiliate: e-Commerce Software Development
SEE: http://www.storefront.net/default.asp?REFERER=-201499070

"John S. Ford" <johnsfor...@hotmail.com> wrote in message
news:e#FHiDsgCHA.1996@tkmsftngp10...

Tom Shelton

unread,
Nov 10, 2002, 1:02:21 AM11/10/02
to

"clintonG" <csgal...@REMOVETHISTEXTwi.rr.com> wrote in message
news:#SWEVh5hCHA.1364@tkmsftngp11...

> This is a perfect example why VB developers should cut the
> apron strings and learn C#. None of this garbage applies.
>
> I mean it, I'm just a lowly script kiddie and C# is making so
> much sense to me I can't believe how unjustified my former
> concerns were.
>
> --
> <%= Clinton Gallagher
> A/E/C Consulting, Web Design, e-Commerce Software Development
> Wauwatosa, Milwaukee County, Wisconsin USA
> NET csgal...@REMOVETHISTEXTmetromilwaukee.com
> URL http://www.metromilwaukee.com/clintongallagher/
>
> LaGarde StoreFront 5 Affiliate: e-Commerce Software Development
> SEE: http://www.storefront.net/default.asp?REFERER=-201499070

You are wrong... Most of it does apply. The problem is that most of the
answers endorse using COM interop to get the desired results, but you will
notice that I posted a solution that makes use of a .NET assembly produced
in another .NET language; JScript.NET, were the desired functionality is
native. You could do this in pure VB.NET or even C#, but it would be much
more difficult then just referencing a simple assembly created in
JScript.NET.

Tom Shelton


John S. Ford

unread,
Nov 12, 2002, 10:24:31 AM11/12/02
to
Thanks for the idea Tom. Unfortunately, I'm working with VB .NET Standard
so I don't have access to the JScript compiler.

John

"Tom Shelton" <to...@dakcs.com> wrote in message
news:uAAffcOhCHA.2592@tkmsftngp09...

Tom Shelton

unread,
Nov 13, 2002, 10:22:27 PM11/13/02
to

"John S. Ford" <johnsfor...@hotmail.com> wrote in message
news:#Gt191liCHA.1840@tkmsftngp08...

> Thanks for the idea Tom. Unfortunately, I'm working with VB .NET Standard
> so I don't have access to the JScript compiler.
>
> John

John,

I'm pretty sure you do actually. If I remember right, VB.NET standard still
installs the entire Framework SDK - which the JScript.NET compiler is part
of. Even with VS.NET EA you have to run the jscript compiler from the
command line. Do a search on your system for jsc.exe, I'd be willing to bet
it is there...

Really, if you can use this method, it will be much better from a
performance, and from a deployment standpoint.

Tom Shelton


Ravichandran J.V.

unread,
Nov 14, 2002, 1:50:18 AM11/14/02
to
//Dim Answer as Double
//Answer = Function("(10 + 6) / 8")

//where Answer gets the value 2. I seem to recall a function that could
do
//this in VBA. Thanks in advance!

//dJohn

John,

I tried my hand with the problem using C# and I have come up with the
following program. See if it is of any use to you.

Remember, though, that the program works only for the given string
"(10+6)/8)" and uses INT32 conversion. For Double conversion use
appropriate conversion methods.

using System;
class a
{
public static string s;
public a()
{
s=null;
}
public static void Test(string str)
{
char ch=' ';
int ctr=0;
ch=str[ctr];
while (ch!=null)
{
ctr++;
}
Console.WriteLine(ctr);
}
public static void Main()
{
Test(s);

Ravichandran J.V.

unread,
Nov 14, 2002, 1:50:22 AM11/14/02
to
Sorry ! I posted the .txt file and not the .cs file. Here is the correct
post. Please ignore the previous post.

//Dim Answer as Double
//Answer = Function("(10 + 6) / 8")

//where Answer gets the value 2. I seem to recall a function that could
do
//this in VBA. Thanks in advance!

//dJohn

John,

I tried my hand with the problem using C# and I have come up with the
following program. See if it is of any use to you.

Remember, though, that the program works only for the given string
"(10+6)/8)" and uses INT32 conversion. For Double conversion use

appropriate conversion methods. I have used lots of variables as I coded
in a hurry without much thought to the finer nuances. I hope you don't
mind the disregard to naming conventions either.

using System;
class a
{
public static string s;
public a()
{
s=null;
}
public static void Test(string str)
{
char ch=' ';

int ctr=1,plusctr=0,slashctr=0,result=0;
string s1=null,s2=null,s3=null,s4=null;
bool plusSign=false,divSign=false,flag=false;
while (ch!='\n')
{
ch=str[ctr];
if (ch!='('){
if (ch!=')'){
s1+=ch;
}
}
ctr++;
}
//Console.WriteLine( s1);
s1+='\n';
ctr=0;
while (flag==false){
if (s1[ctr]=='+'){
//Console.WriteLine(s2.ToInt32());
int plus=s2.ToInt32();
plusSign=true;
plusctr=ctr;
flag=true;
if (s1[ctr]=='-'){
if ( s1[ctr]=='*'){
if (s1[ctr]=='/'){
}
}
}
}
else{
s2+=s1[ctr];
}
ctr++;
}
ctr=plusctr+1;
while (flag==true)
{
if (s1[ctr]=='/'){
slashctr=ctr;
divSign=true;
flag=false;
}
else{
s3+=s1[ctr];
}
ctr++;
}
ctr=slashctr+1;
while (flag==false)
{
if (s1[ctr]=='\n')
{
flag=true;
}
else{
s4+=s1[ctr];
}
ctr++;
}
if (plusSign==true)
{
result=s2.ToInt32()+s3.ToInt32();
}
if (divSign==true)
{
result=result/s4.ToInt32();
}
Console.WriteLine( result);
}
public static void Main()
{
Test("(10+6)/8\n");
}
}

//Dim Answer as Double
//Answer = Function("(10 + 6) / 8")

//where Answer gets the value 2. I seem to recall a function that could
do
//this in VBA. Thanks in advance!

//dJohn

with regards,

Ravichandran J.V.

unread,
Nov 14, 2002, 1:58:32 AM11/14/02
to
//Dim Answer as Double
//Answer = Function("(10 + 6) / 8")

//where Answer gets the value 2. I seem to recall a function that could
do
//this in VBA. Thanks in advance!

//dJohn

Sorry for posting twice or thrice. Here is the correct one. The first
was a mispost; the second was a correct post too but I was not sure if
it was posted or not; this is a confirmation post. Sorry for any
confusion caused !

with regards,

Smartdevil

unread,
Nov 18, 2002, 12:17:32 PM11/18/02
to
Dosent "Int32.Parse" command converts a string to a number ( integer,
double, float )

"clintonG" <csgal...@REMOVETHISTEXTwi.rr.com> wrote in message
news:#SWEVh5hCHA.1364@tkmsftngp11...

0 new messages