JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Converting Strings to Numbers and Back Again

You're all set to write your calculator program, SuperDuperDeluxeCalc, in Visual Basic—but suddenly you realize that the user will be entering numbers in text form, not in numeric form! How can you translate text into numbers—and then numbers into text—to display your results?

It's common in Visual Basic to have to convert values from numbers to strings or from strings to numbers, and it's easy to do. You can use the Str to return a string representation of a number, and you use Val to convert a string to a number. That's all there is to it, but it's easy to forget those two functions, so I'm including them here for reference. Here's an example that converts a string into a number and then back into a string:

Module Module1
    Sub Main()
        Dim strText1 As String = "1234"
        Dim intValue1 As Integer
        intValue1 = Val(strText1)
        strText1 = Str(intValue1)
    End Sub
End Module

Besides Str and Val, you can also use Format and String.Format, which let you format expressions and convert them to string form.

Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor