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.
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.
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.
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.
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.
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' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With