1

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;
    }
}
K.Z
  • 5,201
  • 25
  • 104
  • 240
  • Do you have an exception thrown before TryParse ? Have you tried to remove spaces before and after your number : cleanNumber = Regex.Replace(number.Trim(), @"\s+", ""); ? – Gambi Jan 16 '21 at 09:36
  • no it did not throw any exception – K.Z Jan 16 '21 at 09:37

2 Answers2

1

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

user1672994
  • 10,509
  • 1
  • 19
  • 32
1

Well i dont know why you complicate things but this should be really very easy to solve

public int ConvertToInt(string n) {
  // Trim should solve your case where the number end or start with whitespace. but just  
  // incase i did the replace thing to if there is any whitespace between the numbers. 
  // So its upp to you if you want to retaine the replace or not.
  n = n?.Replace(" ", "").Trim();
  if (Int.TryParse(n, var out number))
    return number;
  else return 0;

}
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31