Saturday, 19 January 2013

Determine is String is Number VB.NET

Deltermine is String is Number VB.NET

Every type has Parse and TryParse methods to convert from String to Appropriate type.

Parse Method gives exception object,user can inspect exception details

TryParse method gives success means  string is converted to appropriate type, No Exception object here.



     Public Shared Sub Main()
    Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
    Thread.CurrentThread.CurrentUICulture = New CultureInfo(1033)
    Dim nd As New Numbersdemo()

    Dim str As [String] = "67577"
    Console.WriteLine("{0} is{1}", str, nd.IsStringisNumber(str))
    'True
    str = "66776.77"
    Console.WriteLine("{0} is{1}", str, nd.IsStringisNumber(str))
    'True
    str = "66776.77.77"
    Console.WriteLine("{0} is{1}", str, nd.IsStringisNumber(str))
    'FALSE
    str = "66776.77"
    Console.WriteLine("{0} is{1}", str, nd.IsStringisNumber(str))
    'True
    str = "66,776.77"
    Console.WriteLine("{0} is{1}", str, nd.IsStringisNumber(str))
    'True
    str = "66,7,76.77"
    Console.WriteLine("{0} is{1}", str, nd.IsStringisNumber(str))
    'True
    str = "-66,7,76.77"
    Console.WriteLine("{0} is{1}", str, nd.IsStringisNumber(str))
    'True
    str = "$66776.77-"
    Console.WriteLine("{0} is{1}", str, nd.IsStringisNumber(str))
    'FALSE
    Dim result As Decimal
    'Method 2
    Try
        'Suppose  financial data in human readable format, in that case NumberStyles class (part of System.Globalization) must be used to parse strings.
        'for ex: this string has currency symbol and trailing - sign.
        'you need to specify appropriate Enum flags or  NumberStyles.Any

        str = "$66776.77-"
        result = [Decimal].Parse(str, NumberStyles.AllowCurrencySymbol Or NumberStyles.AllowTrailingSign Or NumberStyles.AllowDecimalPoint)
            'TRUE
        Console.WriteLine("{0} is{1}", str, result)
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
    'Method 3

    If [Decimal].TryParse(str, NumberStyles.AllowCurrencySymbol Or NumberStyles.AllowTrailingSign Or NumberStyles.AllowDecimalPoint, New CultureInfo("en-US"), result) Then
        Console.WriteLine("Sucess")
    Else
        Console.WriteLine("failed")
    End If

End Sub


'This method checks wether string is number or not.
'
Private Function IsStringisNumber(str As [String]) As Boolean

    Dim result As Decimal
    Return [Decimal].TryParse(str, result)
End Function


Tags: Determine is String is Number VB.NET,Check String is Number Vb.NET,Convert String to Number Vb.NET,How to check wether string is numeric,How to identify if string is Number