在 ASP.NET 核心中使用 NumberFormat 属性

Using NumberFormat property in ASP.NET Core

The localization system has changed quite a bit in ASP.NET CoreCurrentCulture 在当前线程中不再可用。

我正在尝试按照 here 的说明设置 NumberFormat 属性 of CurrentCulture,以便自定义显示货币的格式,但显然它不再可能那样。那么如何为 CurrentCulture 设置 NumberFormat 属性 呢?

asp.net核心之前用于此的代码:

CurrentCulture modified = new CultureInfo(Thread.CurrentThread.CurrentCulture.Name);
Thread.CurrentThread.CurrentCulture = modified;
var numberFormat = modified.NumberFormat;
numberFormat.CurrencySymbol = "RM";
numberFormat.CurrencyDecimalDigits = 2;
numberFormat.CurrencyDecimalSeparator = ".";
numberFormat.CurrencyGroupSeparator = ",";

然后例如在我的代码中我想做的某处:

string fMoney;
fMoney = money.ToString("C");
return fMoney;

并期望应用 numberFormat 设置。

可以在Startup.cs中的Configure()方法中添加UseRequestLocalization:

    public void Configure(IApplicationBuilder app)
    {
        app.UseIISPlatformHandler();
        app.UseRequestLocalization(new RequestCulture(new CultureInfo("es")));
        app.Run(async (context) =>
        {
            context.Response.ContentType = "text/html";
            await context.Response.WriteAsync(HtmlEncoder.Default.HtmlEncode(1000.5f.ToString("C")));
        });
    }

结果:

1.000,50 €

此外,更切合原问题的要点:

    public void Configure(IApplicationBuilder app)
    {
        app.UseIISPlatformHandler();

        var modified = new CultureInfo(CultureInfo.DefaultThreadCurrentCulture.DisplayName);
        modified.NumberFormat.CurrencySymbol = "RM";
        modified.NumberFormat.CurrencyDecimalDigits = 2;
        modified.NumberFormat.CurrencyDecimalSeparator = ".";
        modified.NumberFormat.CurrencyGroupSeparator = ",";

        app.UseRequestLocalization(new RequestCulture(modified));
        app.Run(async (context) =>
        {
            context.Response.ContentType = "text/html";
            await context.Response.WriteAsync(HtmlEncoder.Default.HtmlEncode(1000.5f.ToString("C")));
        });
    }

结果:

RM1,000.50