Emil Davtyan Emil Davtyan - 1 month ago 5
C# Question

Convert.ToInt32() a string with Commas

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.

CMS CMS
Answer

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'
}
Comments