Same different result code (Visual Studio 2012 X dotnetfiddle.net)

2

Follow the image with the results on both platforms, is there any explanation or is it a bug in the online compiler?

Both are console application , the only difference is that VS is being compiled with dotNet4 while dotnetfiddle.net dotnet4.5

    var textBoxValor = "10.8";
    decimal variavel = Decimal.Parse(textBoxValor.Replace(".", ","));

    textBoxValor = "10.8";
    var variavel2 = Decimal.Parse(textBoxValor);

As the image is not good, it follows the result obtained respectively in VS and dotnetfiddle.net dotnetfiddle.net

  

VS: variable: 10.8 variable2: 108

     

dotnetfiddle.net: variable: 108 variable2: 10.8

    
asked by anonymous 20.04.2015 / 21:44

1 answer

3

The difference exists because of the culture in which the program is running.

Your program in VS has a pt-BR culture, which has decimal separator the comma (','), whereas in dotnetfiddle the culture is probably in en-US , which in turn it counts with the point '.' such as the decimal separator.

To always receive the same result, you need to use the overload of the Decimal.Parse method that receives a IFormatProvider as a parameter. If Decimal.Parse is used without this overload the culture in which the program is running is used. That's why when you convert the value 10.8 to dotnetfiddle it becomes 108 because the "," is not the decimal separator of Culture in which the program is running there.

Examples of using Decimal.Parse with the crop specification to be used:

Decimal.Parse(textBoxValor, System.Globalization.CultureInfo.InvariantCulture);

or

Decimal.Parse(textBoxValor, System.Globalization.CultureInfo.GetCultureInfo("pt-BR"));
Decimal.Parse(textBoxValor, System.Globalization.CultureInfo.GetCultureInfo("en-US"));

etc ...

    
20.04.2015 / 21:49