Saturday, 19 January 2013

Determine is String is Number C#

Deltermine is String is Number C#

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 static void Main()
        {
        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(1033);
        Numbersdemo nd = new Numbersdemo();

        String str = "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
        decimal result;

  //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 | NumberStyles.AllowTrailingSign| NumberStyles.AllowDecimalPoint);
    Console.WriteLine("{0} is{1}",str,result); //TRUE
        }
        catch (Exception ex)
        {
        Console.WriteLine(ex.Message);
        }
 //Method 3
        if (Decimal.TryParse(str, NumberStyles.AllowCurrencySymbol |
NumberStyles.AllowTrailingSign|NumberStyles.AllowDecimalPoint,
new CultureInfo("en-US"), out result))
            Console.WriteLine("Sucess");
        else Console.WriteLine("failed");

        }
//This method checks wether string is number or not.
//
        bool IsStringisNumber(String str)
        {
           
            decimal result;
            return Decimal.TryParse(str, out result);
        }


Tags: Determine is String is Number C#,Check String is Number C#,Convert String to Number C#,How to check wether string is numeric,How to identify if string is Number