Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# parse int from different locale [duplicate]

Tags:

c#

.net-core

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);
like image 998
monty Avatar asked Mar 11 '26 15:03

monty


2 Answers

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);
like image 65
canton7 Avatar answered Mar 14 '26 05:03

canton7


If you allow thousands separators, it will work:

int.Parse("1,111", NumberStyles.AllowThousands, CultureInfo.GetCultureInfo("en"));
// 1111
like image 33
germi Avatar answered Mar 14 '26 03:03

germi