I know, there are other questions like this e.g. Convert number into culture specific
But I am having a hard time and even the answer doesn't work for me. Still getting System.FormatException: 'Input string was not in a correct format.'
My current/system locale is de and I am parsing an en int. Whatever I tried so far (including answers from previous quesions, does not work.
So, what am I missing?
string numberStr = "1,111"; // one thousand one hundred eleven
//int result = int.Parse(numberStr);
//int result = int.Parse(numberStr, CultureInfo.GetCultureInfo("en-US").NumberFormat);
//int result = int.Parse(numberStr, CultureInfo.InvariantCulture);
//int result = int.Parse(numberStr, CultureInfo.InvariantCulture.NumberFormat);
//int result = int.Parse(numberStr, CultureInfo.GetCultureInfo("en-UK").NumberFormat);
int result = int.Parse(numberStr, CultureInfo.GetCultureInfo("en"));
Console.WriteLine(result);
Your problem is simply that int.Parse(string) and int.Parse(string, IFormatProvider) don't allow a thousands separator.
You can see this in the Remarks section of the doc:
The
sparameter contains a number of the form:[ws][sign]digits[ws]
You can however, use the int.Parse(string, NumberStyles), overload, which lets you specify NumberStyles.
If we peek at the source for int.Parse(string), we can see that it effectively calls int.Parse(string, NumberStyles.Integer).
If you look at the docs for NumberStyles, we want Integer, but also AllowThousands. We don't want to go as far as Number, because that includes AllowDecimalPoint, and integers can't have decimal points.
int result = int.Parse("1,111", NumberStyles.Integer | NumberStyles.AllowThousands);
You probably also want to specify a culture, because the thousands separator depends on culture (e.g. German uses . as the thousands separator). The invariant culture uses ,, as does en:
int result = int.Parse(
"1,111",
NumberStyles.Integer | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture);
If you allow thousands separators, it will work:
int.Parse("1,111", NumberStyles.AllowThousands, CultureInfo.GetCultureInfo("en"));
// 1111
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