logo VB.Net - String to Number
Guide Contents
DigitalDan Home Page

Programmers are often faced with a text string comprising of numeric digits. They may wish to decide what number the string reprsents and then load the number into a numeric variable (single, double, integer etc.) VB.Net has built in functions to convert text strings containing digits into each type of number variable.
 
This example examines the striing "text1"
if string "text1" represents a valid integer then it returns true AND loads the numeric value from text into integer "integ1"
If string "text1" does not represent an integer then it returns false and leaves the integer "integ1" unchanged

 
Private Function IntegerParse(text1 as string) as Boolean
Dim integ1 as integer
Return Integer.TryParse(text1,integ1)
End Function

 
Programmers will often be told to use a "default" value for the number whenever it cannot be extracted from the string. This function will try to extract a number from text1 but fall back to a default value of 0 when text1 cannot be converted to integer.
 
Private Function IntegerParse(text1 As String) As Integer
Dim integ1 as Integer
If Not Integer.TryParse(text1, Integ1) then integ1 = 0
Return integ1
End Function

 
The following code snippets illustrate that .TryParse can work with any of the standard numeric variable types
 
Dim by1 As Byte : If Not Byte.TryParse(text, by1) Then by1 = 0
Dim in1 As Integer : If Not Integer.TryParse(text, in1) Then in1 = 0
Dim lo1 As Long : If Not Long.TryParse(text, lo1) Then lo1 = 0
Dim de1 As Decimal : If Not Decimal.TryParse(text, de1) Then de1 = 0
Dim si1 As Single : If Not Single.TryParse(text, si1) Then si1 = 0
Dim do1 As Double : If Not Double.TryParse(text, do1) Then do1 = 0

 
Although TryParse is very reliable, it has one quirk you should be aware of - the quirk only affects the Single and Double variants of TryParse.
Dim do1 As Double : If Not Double.TryParse("1E2", do1) Then do1 = 0
will return true (1E2 is a valid Double number) and place the value 100 into do1
VB.Net uses E to identify an exponent (number of digits to shift decimal point,) and reads 1E2 as 1 followed by move decimal point folowed by 2 places right.
If this behaviour is undesirable, the following adjustment may be required when using Single.TryParse or Double.TryParse
 
Dim si1 As Single : If Not Single.TryParse(text.Replace("e", "Z", StringComparison.InvariantCultureIgnoreCase), si1) Then si1 = 0
Dim do1 As Double : If Not Double.TryParse(text.Replace("e", "Z", StringComparison.InvariantCultureIgnoreCase), do1) Then do1 = 0

 
This fix works beacuse e (upper case E or lower case e) is the only letter used for exponents.
The .Replace forces a Z into the text before the numeric check and any string with a Z will be classified as not-numeric. The StringComparison..... modifier endures that any "e" (lowercase "e" or uppercase "E") will be replaced.
DigitalDan.co.uk ... Hits = 409