Reputation: 1037
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?
Upvotes: 12
Views: 7404
Reputation: 115518
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.
Upvotes: 1
Reputation: 9412
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
}
Upvotes: 30
Reputation: 707
You can't have separators, just numbers 0 thru 9, and an optional sign.
http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx
Upvotes: 0
Reputation: 357
Because you're supposed to specify a string containing a plain integer number (maybe preceded by +/- sign), with no thousands separator. You have to replace the separator befor passing the string to the ToInt32 routine.
Upvotes: 0