Emil Davtyan Emil Davtyan - 1 year ago 140
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.

Answer Source

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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download