Tuesday, April 11, 2006

Visual Basic: Integer to String/String to Integer Conversions

Someone asked how to convert from an integer to string in Visual Basic/VBA. The answer, Visual Basic will do this automatically. Observe the following code:

Sub test()
    Dim i As Integer
    Dim s As String
    
    i = 5
    s = i
    MsgBox s, vbOKOnly, "Test"
End Sub

In the above code, I will automatically be converted to a String, no extra code is necessary. Technically, it could be re-written as:

Sub test()
    Dim i As Integer
    
    i = 5
    MsgBox i, vbOKOnly, "Test"
End Sub

However, I feel that using the intrinsic functions of Val() and Str() are a little better since it clearly shows that you are converting from one type to another. Observe the below code:

Sub test()
    Dim i As Integer
    Dim s As String
    
    i = 5
    s = Str(i)
    MsgBox s, vbOKOnly, "Test"
    
    i = Val(s)
End Sub

Here, we can clearly tell by using the Str() function that we are converting from a number, and vice-versa with the Val() function. I feel that for clear understanding for future maintainers, this is a better approach. Interpreted languages such as VB and Perl that do automatic type conversion promote bad programming practices and I feel that type conversions such as this are a crutch for lazy programmers. I myself am guilty of this since I sometimes make exceptions when I am assigning a value to a textbox, however this is a habit I should break myself of. Programming isn’t just about writing code that works, it is also about writing code that can be maintained and understood by other developers.

10 comments:

Anonymous said...

Thank you!

Unknown said...

conversion of string to an integer?????

Anonymous said...

warning: str inserts white space.... just to give you another problem to solve.

wouldn't want you getting bored or anything.

Anonymous said...

str to int -> val()

Anonymous said...

but when i enter:

ascii3=173
length=Len(ascii3)


i get length = 4

Te4t0n said...

Use cstr()

or Trim(str(123))

oNeLe said...

how to convert the integer to text, for example 5 to "*****"..?
using do while or do until or for next,,

tq very2 much..

Anonymous said...

Thanks. I was getting an error concantenating an integer to a string. I needed to explicitly cast the integer as a string for the concantenation to work, and this tip did the trick.

Kai_Strife said...

Thank you. I've been searching for this for a while now.

Anonymous said...

how to remove that extra space generated by str()... i want to cnvert int to string in a path and that space is causing problem.. help me