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:

  1. Anonymous9:43 AM

    Thank you!

    ReplyDelete
  2. conversion of string to an integer?????

    ReplyDelete
  3. Anonymous5:35 AM

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

    wouldn't want you getting bored or anything.

    ReplyDelete
  4. Anonymous7:12 AM

    str to int -> val()

    ReplyDelete
  5. Anonymous1:28 PM

    but when i enter:

    ascii3=173
    length=Len(ascii3)


    i get length = 4

    ReplyDelete
  6. Use cstr()

    or Trim(str(123))

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

    tq very2 much..

    ReplyDelete
  8. Anonymous12:11 PM

    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.

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

    ReplyDelete
  10. Anonymous7:48 AM

    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

    ReplyDelete