Skip to content
AgileLogics
5 min read

Type Conversion

Prerequisites: Data types

Values often need converting — text typed by a user into a number, a number into text for display.

Widening and narrowing

A widening conversion can't lose information (Integer to Long or Double), so VB does it automatically. A narrowing conversion might (Double to Integer, String to Integer). With Option Strict On, narrowing requires an explicit conversion:

Module Program
    Sub Main()
        Dim small As Integer = 7
        Dim wide As Double = small      ' widening: fine
        Dim text As String = "42"
        Dim n As Integer = text         ' narrowing: not allowed
    End Sub
End Module
main.vb(6) : error BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'.

        Dim n As Integer = text         ' narrowing: not allowed
                           ~~~~

Conversion functions

Module Program
    Sub Main()
        Console.WriteLine(CInt("42") + 1)
        Console.WriteLine(CInt(2.5))
        Console.WriteLine(CInt(3.5))
        Console.WriteLine(Fix(3.7))
        Console.WriteLine(CDbl("3.25") * 2)
        Console.WriteLine(CDec(10) / 4)
        Console.WriteLine(CStr(99) & "!")
        Console.WriteLine(CBool("True"))
        Console.WriteLine(CType("15", Integer) * 2)
        Console.WriteLine(Convert.ToInt32("7") + 1)
        Console.WriteLine(Integer.Parse("123") + 1)
    End Sub
End Module
43
2
4
3
6.5
2.5
99!
True
30
8
124
  • CInt, CLng, CDbl, CDec, CStr, CBool, CDate, CChar are built-in conversion functions; CType(value, Type) is the general form.
  • CInt rounds to the nearest whole number, and exact halves go to the nearest even number (banker's rounding): CInt(2.5) is 2, CInt(3.5) is 4. Fix and Int drop the fraction instead.
  • CDbl("3.25") uses the computer's regional settings, so in a country that writes 3,25 it reads the text differently. For data files, use Double.Parse(text, CultureInfo.InvariantCulture).

Safe parsing with TryParse

CInt("abc") throws an exception. When text comes from a user or a file, use TryParse, which returns True or False and puts the result in a variable you pass in:

Module Program
    Sub Main()
        For Each entry In {"42", "abc", "  7 "}
            Dim value As Integer
            If Integer.TryParse(entry, value) Then
                Console.WriteLine($"'{entry}' -> {value}")
            Else
                Console.WriteLine($"'{entry}' is not a number")
            End If
        Next
    End Sub
End Module
'42' -> 42
'abc' is not a number
'  7 ' -> 7

Numbers to text

Module Program
    Sub Main()
        Dim n = 255
        Console.WriteLine(n.ToString())
        Console.WriteLine(n.ToString("D5"))
        Console.WriteLine(n.ToString("X"))
        Console.WriteLine(Convert.ToString(n, 2))
    End Sub
End Module
255
00255
FF
11111111

"D5" pads to five digits and "X" is hexadecimal; Convert.ToString(n, 2) gives binary.

Practice

Parse the strings "19", "x", and "23" with Integer.TryParse, add up the ones that are valid, and print the total and how many were skipped.

Show solution
Module Program
    Sub Main()
        Dim total = 0
        Dim skipped = 0
        For Each s In {"19", "x", "23"}
            Dim n As Integer
            If Integer.TryParse(s, n) Then
                total += n
            Else
                skipped += 1
            End If
        Next
        Console.WriteLine($"Total: {total}, skipped: {skipped}")
    End Sub
End Module
Total: 42, skipped: 1