I want to convert a thousand separated value to integer but am getting one exception.
double d = Convert.ToDouble("100,100,100");
is working fine and getting d=100100100
int n = Convert.ToInt32("100,100,100");
is getting one format exception
Input string was not in a correct format
Why?
To convert a comma separated string to a numeric array:Call the split() method on the string to get an array containing the substrings. Use the map() method to iterate over the array and convert each string to a number. The map method will return a new array containing only numbers.
To parse a string with commas to a number: Use the replace() method to remove all the commas from the string. The replace method will return a new string containing no commas. Convert the string to a number.
try this:
int i = Int32.Parse("100,100,100", NumberStyles.AllowThousands);
Note that the Parse
method will throw an exception on an invalid string, so you might also want to check out the TryParse
method as well:
string s = ...;
int i;
if (Int32.TryParse(s, NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out i))
{
// if you are here, you were able to parse the string
}
What Convert.ToInt32 is actually calling in your example is Int32.Parse.
The Int32.parse(string)
method only allows three types of input: white space, a sign, and digits. In the following configuration [ws][sign]digits[ws] (in brackets are optional).
Since your's contained commas, it threw an exception.
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