Search code examples
c#asp.net-core-3.1globalization

Configure .Net Core 3 web API to always parse numbers with invariant Culture


I don't know whether the title makes sense, but in short we need to parse doubles passed as strings. but we don't have control over the format of the numbers (e.g. period vs comma decimal separators)

So, we have a need to parse certain text fields using Invariant Culture and Number Styles, like so:

double.TryParse(ResponseObject.Ammount, 
                NumberStyles.Any, 
                CultureInfo.InvariantCulture, 
                out double amt);

Thing is, it's pretty hard to enforce the use of this overloaded method everywhere. So I am hoping you can configure the use of the invariant culture in Startup.cs, however I don't really know how to do that.

config in Startup:

private void ConfigureLocalization(IServiceCollection services)
        {
            var jsonLocalizationOptions = Configuration.GetSection(nameof(JsonLocalizationOptions));

            _jsonLocalizationOptions = jsonLocalizationOptions.Get<JsonLocalizationOptions>();
            _defaultRequestCulture = new RequestCulture(_jsonLocalizationOptions.DefaultCulture,
                _jsonLocalizationOptions.DefaultUICulture);
            _supportedCultures = _jsonLocalizationOptions.SupportedCultureInfos.ToList();

            services.AddJsonLocalization(options =>
            {
                options.ResourcesPath = _jsonLocalizationOptions.ResourcesPath;
                options.UseBaseName = _jsonLocalizationOptions.UseBaseName;
                options.CacheDuration = _jsonLocalizationOptions.CacheDuration;
                options.SupportedCultureInfos = _jsonLocalizationOptions.SupportedCultureInfos;
                options.FileEncoding = _jsonLocalizationOptions.FileEncoding;
                options.IsAbsolutePath = _jsonLocalizationOptions.IsAbsolutePath;
            });
        }

(I can't say much more about the project, but let's just say that we have to parse certain strings which contain doubles, etc. There's no way around what we're doing here, only straight through).


Solution

  • So anyway, this is the solution if we can't configure it in startup.

        public static class ParseUtil
        {
            public static decimal ParseDecimal(string input)
            {
                return decimal.TryParse(input,
                                     NumberStyles.Any,
                                     CultureInfo.InvariantCulture,
                                     out decimal amt) ? amt : 0;
            }
    
            public static double ParseDouble(string input)
            {
                return double.TryParse(input,
                                     NumberStyles.Any,
                                     CultureInfo.InvariantCulture,
                                     out double amt) ? amt : 0;
            }
        }