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.
1,500
You can use int.Parse and add NumberStyles.AllowThousands :
int.Parse
NumberStyles.AllowThousands
int num = int.Parse(toParse, NumberStyles.AllowThousands);
Or int.TryParse , letting you know if the operation succeeded:
int.TryParse
int num; if (int.TryParse(toParse, NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out num)) { // parse successful, use 'num' }
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.
Decimal.Parse()
int
CultureInfo
You can do replace(';', '') before converting it to int.
replace(';', '')
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)
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.
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.
String.Empty
Convert.ToInt32()
Int32.Parse()
Int32.TryParse()
Int32.Parse
Int32.TryParse
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