Friday, March 5, 2010

VBScript Type Conversion

It's very often for people who are interested in VBScripting to encounter the problem of type conversion from string to number. There is no predefined method that could be found to convert the string variable type to numeric.
We can use the "FormatNumber" for the conversion into Float type. But, this case fails if there is an addition operation. For Example: Consider the code below:

Dim Var01, Var02

Var01 = FormatNumber(InputBox("Enter a Number"))
Var02 = FormatNumber(InputBox("Enter another Number"))

MsgBox "Sum is " & Var01 + Var02

The output of this code that one expects would be the sum, to be returned. But if we input values 2 and 3 here, then the output will be displayed as 2.003.00, instead of 5. This is because the effective action which gets performed is string concatenation, rather than addition of two numbers.

Now, how to perform such an action then? Well, we need to adopt a different method in order to achieve this! Just perform an addition of a zero to the Variable, and all goes fine. Now the code should be:


Dim Var01, Var02

Var01 = FormatNumber(InputBox("Enter a Number"))
Var02 = FormatNumber(InputBox("Enter another Number"))
Var02 = Var02 + 0

MsgBox "Sum is " & Var01 + Var02

Now the code works completely fine. This piece of code returns the sum as "5" for inputs 2 and 3.

So the solution for the addition issue is that you add a 0 to the string variable that has been accepted from an input box. Hereby, we can achieve the task of successful type conversion.

No comments:

Post a Comment