Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToInt32() a string with Commas

Tags:

c#

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.

like image 221
Emil Davtyan Avatar asked Dec 01 '09 06:12

Emil Davtyan


People also ask

What does convert ToInt32 do in C#?

ToInt32() Method in C# This method is used to convert the value of the specified Decimal to the equivalent 32-bit signed integer. A user can also convert a Decimal value to a 32-bit integer by using the Explicit assignment operator.

What is the difference between int TryParse () & Convert ToInt32 () in C#?

Int32 type. The Convert. ToInt32 method uses Parse internally. The Parse method returns the converted number; the TryParse method returns a boolean value that indicates whether the conversion succeeded, and returns the converted number in an out parameter.

What is ToInt32 ()?

ToInt32(Object) Converts the value of the specified object to a 32-bit signed integer. ToInt32(SByte) Converts the value of the specified 8-bit signed integer to the equivalent 32-bit signed integer.

Does convert ToInt32 round up or down?

Round method. Of course Convert. ToInt32() does use this method already with the behavior described. It has to do with averages, you convert and add 6 numbers and half of them are rounded down and the other half are roudned up you get a more accurate number then if everything was rounded up or rounded down.


1 Answers

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' } 
like image 194
Christian C. Salvadó Avatar answered Oct 05 '22 23:10

Christian C. Salvadó