我知道,还有其他类似的问题 例如Convert number into culture specific
但我很难过,甚至答案对我来说也不起作用。还在得到 System.FormatException:“输入字符串的格式不正确。”
我当前/系统区域设置是 de,我正在解析 en int。到目前为止我尝试过的任何方法(包括之前问题的答案)都不起作用。
那么,我错过了什么?
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);
最佳答案
您的问题很简单,int.Parse(string)
和 int.Parse(string, IFormatProvider)
不允许使用千位分隔符。
您可以在the doc的备注部分看到这一点:
The
s
parameter contains a number of the form:[ws][sign]digits[ws]
但是,您可以使用 int.Parse(string, NumberStyles)
,重载,它允许您指定 NumberStyles
.
如果我们查看 the source for int.Parse(string)
,我们可以看到它有效地调用了 int.Parse(string, NumberStyles.Integer)
。
如果您查看 NumberStyles
的文档,我们需要 Integer
,但也需要 AllowThousands
。我们不想深入到 Number
,因为它包括 AllowDecimalPoint
,而且整数不能有小数点。
int result = int.Parse("1,111", NumberStyles.Integer | NumberStyles.AllowThousands);
您可能还想指定一种区域性,因为千位分隔符取决于区域性(例如,德语使用 .
作为千位分隔符)。不变区域性使用 ,
,en
也是如此:
int result = int.Parse(
"1,111",
NumberStyles.Integer | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture);
关于C# 从不同语言环境解析 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59881624/