Number Parsing in Visual Basic .NET

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Visual Basic .NET.

Imports System

Module NumberParsing
    Sub Main()
        ' With Double.Parse, we can parse floating-point numbers
        Dim f As Double = Double.Parse("1.234")
        Console.WriteLine(f)

        ' For Integer.Parse, we can parse integer numbers
        Dim i As Integer = Integer.Parse("123")
        Console.WriteLine(i)

        ' Integer.Parse will recognize hex-formatted numbers with "0x" prefix
        Dim d As Integer = Convert.ToInt32("0x1c8", 16)
        Console.WriteLine(d)

        ' UInteger.Parse is available for parsing unsigned integers
        Dim u As UInteger = UInteger.Parse("789")
        Console.WriteLine(u)

        ' Integer.Parse is used for basic base-10 integer parsing
        Dim k As Integer = Integer.Parse("135")
        Console.WriteLine(k)

        ' Parse functions throw an exception on bad input
        Try
            Dim badNumber As Integer = Integer.Parse("wat")
        Catch e As FormatException
            Console.WriteLine(e.Message)
        End Try
    End Sub
End Module

The System namespace provides the number parsing functionality in Visual Basic .NET.

With Double.Parse, we can parse floating-point numbers. Unlike Go, we don’t need to specify the bit precision as it’s determined by the Double type.

For Integer.Parse, we can parse integer numbers. Visual Basic .NET doesn’t require specifying the base or bit size for standard integer parsing.

To parse hexadecimal numbers, we use Convert.ToInt32 with base 16. Visual Basic .NET doesn’t automatically recognize the “0x” prefix, so we need to handle it explicitly.

UInteger.Parse is available for parsing unsigned integers.

Integer.Parse is used for basic base-10 integer parsing, similar to Go’s Atoi function.

Parse functions in Visual Basic .NET throw exceptions on bad input, rather than returning an error. We use a Try-Catch block to handle these exceptions.

To run the program, save it as NumberParsing.vb and use the Visual Basic compiler:

$ vbc NumberParsing.vb
$ NumberParsing.exe
1.234
123
456
789
135
Input string was not in a correct format.

Next, we’ll look at another common parsing task: URLs.