Vahid Amiri
Vahid Amiri

Reputation: 11117

Using NumberFormat property in ASP.NET Core

The localization system has changed quite a bit in ASP.NET Core. The CurrentCulture is no longer available in the current thread.

I'm trying to set NumberFormat property of CurrentCulture as explained here, in order to customize the format for displaying money but obviously it's no longer possible that way. So how does one set the NumberFormat property for CurrentCulture?

The code that used to work for this before asp.net core:

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 = ",";

Then for example somewhere in my code I want to do:

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

and expect the numberFormat settings to be applied.

Upvotes: 4

Views: 2178

Answers (1)

Leonardo Herrera
Leonardo Herrera

Reputation: 8406

You can add UseRequestLocalization to the Configure() method in Startup.cs:

    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")));
        });
    }

Result:

1.000,50 €

Also, more to the point of the original question:

    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")));
        });
    }

Result:

RM1,000.50

Upvotes: 5

Related Questions