Emil Davtyan Emil Davtyan - 7 days ago 4x
C# Question

Convert.ToInt32() a string with Commas

I have a string that sometimes has commas seperating the number like

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.


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'