Convert.ToInt32() a string with Commas

c#

Solution

You could use `int.Parse` and add the `NumberStyles.AllowThousands` flag:

int num = int.Parse(toParse, NumberStyles.AllowThousands);

Or `int.TryParse` letting you know if the operation succeeded:

int num;
if (int.TryParse(toParse, NumberStyles.AllowThousands,
                 CultureInfo.InvariantCulture, out num))
{
    // parse successful, use 'num'
}

Problem

I have a string that sometimes has commas seperating the number like `1,500` and I need to convert this to an Int, currently it is throwing an exception, can someone tell me how to fix this so that sometimes I may input numbers with commas and other times with out commas and it will still convert.

Original source