简体   繁体   中英

.net core app parsing decimals in a linux docker container

The following code, in a .net core 2.0.0 app works fine when the app is run on the windows development machine. When the app is deployed in a linux docker container, it fails with exception message: System.FormatException: 'Input string was not in a correct format.'

Why? And what's the workaround?

class Program {
    static void Main(string[] args) {
        var value = "$291.00";
        var valueAsDecimal = decimal.Parse(value, System.Globalization.NumberStyles.Any);
        Console.WriteLine(valueAsDecimal);
        Console.ReadLine();
    }
}

The currency sign is locale specific. Have you checked what the Culture settings are?

If you always want to use '$' and '.' then use a format provifeer.

 var valueAsDecimal = decimal.Parse(
     value, 
     NumberStyles.Any, 
     new CultureInfo("en-AU");

Here's the code that worked. I had to manually set the correct culture. Thanks Richard Schneider and Evk for your comments leading the way.

class Program {
    static readonly CultureInfo USEnglish = new CultureInfo("en-US");
    static void Main(string[] args) {
        var value = "$291.00";
        var valueAsDecimal = decimal.Parse(value, System.Globalization.NumberStyles.Any, USEnglish);
        Console.WriteLine(valueAsDecimal);
        Console.ReadLine();
    }
}

It appears that the default culture running on the docker container FROM microsoft/dotnet:2.0-runtime AS base is invariant culture:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM