3

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);
divyang4481
  • 1,584
  • 16
  • 32
monty
  • 7,888
  • 16
  • 63
  • 100
  • 3
    That answer is for *doubles*,that's why the code works immediatelly. With ints, it looks like the default NumberStyles doesn't include thousand separators – Panagiotis Kanavos Jan 23 '20 at 15:15

2 Answers2

9

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 s parameter 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);
Community
  • 1
  • 1
canton7
  • 37,633
  • 3
  • 64
  • 77
5

If you allow thousands separators, it will work:

int.Parse("1,111", NumberStyles.AllowThousands, CultureInfo.GetCultureInfo("en"));
// 1111
germi
  • 4,628
  • 1
  • 21
  • 38