C# 从不同语言环境解析 int

标签 c# .net-core

我知道,还有其他类似的问题 例如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/

相关文章:

c# - 克隆匿名类型?

c# - WPF 和 Paypal 集成

c# - 同一方法.net core web api上的多种类型[FromBody]

.net-core - 未识别为有效的日期时间

c# - .NETStandard 1.1 库中的接口(interface)在 .NET 4.61 中没有实现

c# - MVVM动态添加元素到scrollview

c# - 如何为特定类型而不是全局设置 Json.NET ContractSerializer?

c# - 如何在两个不同的 .NET Core 应用程序之间共享加密数据?

c# - 将 dd/MM/yyyy 输入转换为日期格式的 yyyy-MM-dd,而不是 varchar/datetime

c# - 在 'dotnet' 添加一个带有本地包文件的包