Convert.ToInt32 () semicolon

I have a string that sometimes has a comma separating a number like 1,500 , and I need to convert this to Int, it is currently throwing an exception, can someone tell me how to fix this so that sometimes I can enter comma numbers and other points with commas, and it will still be converted.

+41
c #
Dec 01 '09 at 6:19 06:19
source share
7 answers

You can use int.Parse and add NumberStyles.AllowThousands :

 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' } 
+108
Dec 01 '09 at 6:26
source share

You can use Decimal.Parse() and then apply the result to int . This also works with the current culture, or you can specify CultureInfo to use. There is no need to manually handle commas, decimal points, etc., which are all embedded in .NET.

+6
Dec 01 '09 at 6:26
source share

You can do replace(';', '') before converting it to int.

+2
Dec 01 '09 at 6:22
source share

If you don’t need to worry about the rules for different countries (for example, some use a comma as a decimal place instead of the thousands separator), then just separate the commas first.

eg

 string nastyNumber = "1,234"; int result = int.Parse(nastyNumber.Replace(",", "")); 

(replace int with double if you need a floating point)

+2
Dec 01 '09 at 6:24
source share

What brute force offers to remove commas? What if the string is something like "1,1,1"? Is this a number? Removing commas will make it a valid number and make the conversion semantically incorrect.

There is a reason NumberStyles exist, and the Int.Parse () method can parse with or without style.

+2
Dec 27 '11 at 17:48
source share

You can replace commas with String.Empty before calling Convert.ToInt32() , or you can use Int32.Parse() or Int32.TryParse() with NumberStyles.AllowThousands as one of the parameters.

Int32.Parse

Int32.TryParse

0
Dec 01 '09 at 6:26
source share

You can use code

 int num = Strings.Replace(str, ",", string.Empty); 

This replaces all occurrences of "," with "" (empty string). Thus, 1,000,000 rpm 1,000,000

0
Oct 18 '16 at 17:20
source share



All Articles