Converts string in a specified style and culture-specific format to 32-bit signed integer
Imports System.Globalization
Module StringParsing
Public Sub Main()
Dim numericString As String
Dim styles As NumberStyles
numericString = "1"
styles = NumberStyles.Integer
CallTryParse(numericString, styles)
numericString = "-3"
styles = NumberStyles.None
CallTryParse(numericString, styles)
styles = NumberStyles.AllowLeadingSign
CallTryParse(numericString, styles)
numericString = "3-"
CallTryParse(numericString, styles)
styles = styles Or NumberStyles.AllowTrailingSign
CallTryParse(numericString, styles)
numericString = "$1"
styles = NumberStyles.Integer
CallTryParse(numericString, styles)
styles = NumberStyles.Integer Or NumberStyles.AllowCurrencySymbol
CallTryParse(numericString, styles)
numericString = "1.00"
styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
CallTryParse(numericString, styles)
numericString = "1.72"
styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
CallTryParse(numericString, styles)
numericString = "2,593"
styles = NumberStyles.Integer Or NumberStyles.AllowThousands
CallTryParse(numericString, styles)
numericString = "1E-01"
styles = NumberStyles.Integer Or NumberStyles.AllowExponent
CallTryParse(numericString, styles)
numericString = "1E03"
CallTryParse(numericString, styles)
numericString = "8c1"
CallTryParse(numericString, NumberStyles.HexNumber)
numericString = "0x80C1"
CallTryParse(numericString, NumberStyles.HexNumber)
End Sub
Private Sub CallTryParse(stringToConvert As String, styles AS NumberStyles)
Dim number As Integer
Dim provider As CultureInfo
Dim result As Boolean = Int32.TryParse(stringToConvert, styles,provider, number)
If result Then
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
Else
Console.WriteLine("Attempted conversion of '{0}' failed.",Convert.ToString(stringToConvert))
End If
End Sub
End Module
Related examples in the same category