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

Asked

Viewed 95 times

2

Follows image with the results on both platforms, has some explanation or is a bug in the online compiler?

Both are console application, the only difference is that in VS is being compiled with dotNet4 while the 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, follow the result obtained respectively in VS and website dotnetfiddle.net

VS: variable: 10.8 variable2: 108

dotnetfiddle.net: variable: 108 variable2: 10.8

inserir a descrição da imagem aqui

1 answer

3


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

Your VS show is cultured pt-BR, which has the decimal separator comma (','), while in dotnetfiddle the culture is probably in en-US, which in turn has the '.' point as the decimal separator.

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

Examples of the use of Decimal.Parse with the specification of the crop 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....

  • 1

    I was suspicious of this, is there any way to post a code for how to solve to have the two results equal? Hence mark as conluído. @marciano-Andrade

  • 1

    @Hstackoverflow I edited the answer, take a look.

  • Thanks @marciano-Andrade.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.