Search code examples
c#int32

C# convert XML Node string to Int32


I reading data from webservice and is not clean. I need to convert string to Int where string can be null, number or with white spaces. I make simple program to achieve this but with whitespaces my code does not hit ... If (uint.TryParse(cleanNumber, out ux)) not sure what I am missing from puzzle?

public class Program
{
    static void Main(string[] args)
    {
        string no = "08709079777              ";
        //string no = "0870777777";
        Console.WriteLine("no "+ no);

        Program o = new Program();

       var t1 =  o.ConvertStringToInt32(no);

        Console.WriteLine("t1 "+ t1);
        Console.ReadLine();
    }

    private int ConvertStringToInt32(string number)
    {
        int returnIntVal = 0;
        try
        {
            if (!string.IsNullOrEmpty(number))
            {
                var cleanNumber = Regex.Replace(number, @"\s+", "");

                uint ux;

                if (uint.TryParse(cleanNumber, out ux))
                {
                    returnIntVal = (int)ux;
                }
            }
            else
            {
                returnIntVal = 0;
            }
        }
        catch(Exception exp)
        {
            var ex = exp;
        }
        
        
        return returnIntVal;
    }
}

Solution

  • The number 0870777777 you are trying to parse is beyond int data type range which is -2,147,483,648 to 2,147,483,647. Check the data type ranges at here.

    Use the data type as long (or Int64).

    private static long ConvertStringToInt32(string number)
    {
        long returnIntVal = 0;
        try
        {
            if (!string.IsNullOrEmpty(number))
            {
                var cleanNumber = Regex.Replace(number, @"\s+", "");
                if (long.TryParse(cleanNumber, out long ux))
                {
                    returnIntVal = ux;
                }
            }
            else
            {
                returnIntVal = 0;
            }
        }
        catch(Exception exp)
        {
            var ex = exp;
        }
        
        Console.WriteLine("returnIntVal: " + returnIntVal);
        return returnIntVal;
    }
    

    Check this fiddle - https://dotnetfiddle.net/3Luoon