.netasp.netglobalizationcultureinfo

Creating a NumberFormat for an existing .NET CultureInfo in ASP.NET application


I want to format my numbers throughout the application in a consistent way, no matter what culture is chosen. In fact, it's "non-standard" even for the basic culture that we're using.

I want to format "{1500.50:c}" as: '1500.50', but the standard for my culture 'nl-NL', is: '€ 1.500,00'. We don't have the user-rights, since it's a webapplication, to register custom cultures, therefore we're looking for a runtime solution.

We want a "set and forget" solution. Not a Util class with static (extension) methods, but an application wide solution, so we can continue to use the standard .ToString("c"), or ToString("N") logic, which would follow our custom rules. This would be to alter the .NumberFormat of the Culture, but how? Everything seems to be readonly.

Thanks.


Solution

  • I would create a base class on which all your pages are derived and set the parameters you want for the culture there like so:

    public class PageBase : Page
    {
        protected override void InitializeCulture()
        {
            var culture = CultureInfo.CreateSpecificCulture( CultureInfo.CurrentCulture.Name );
            culture.NumberFormat.CurrencySymbol = string.Empty;
            culture.NumberFormat.NumberDecimalDigits = 2;
            culture.NumberFormat.NumberDecimalSeparator = ".";
            culture.NumberFormat.NumberGroupSeparator = ",";
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
    
            base.InitializeCulture();
        }
    }
    

    Or you could build your culture off an existing one:

    public class PageBase : Page
    {
        protected override void InitializeCulture()
        {
            var culture = CultureInfo.CreateSpecificCulture( "en-US" );
            culture.NumberFormat.CurrencySymbol = string.Empty;
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
    
            base.InitializeCulture();
        }
    }